如果第二个键存在,则首先匹配两个字典并更改键

我有两个dict

a={'a':'A','b':'B'}
b={'a':123,'b':123}

我需要检查 b 中的键 'a' 和 'b'(例如两个元素,在实际代码中,它会更多)是否dict存在于dicta 中。如果是这样,我应该dict使用 a 中的值更改 b 中的键dict

预期结果:

b={'A':123, 'B': 123}

我该怎么做?


回首忆惘然
浏览 148回答 3
3回答

人到中年有点甜

{a[k] if k in a else k: v for k, v in b.items()}

慕后森

由于configParser在大多数情况下都像 dict 一样,我们在这里可以做的是使用key不同的代码块来确保有唯一的块。这是一个简单的测试来展示它的实际效果:import configparserclass Container:    configs=[] # keeps a list of all initialized objects.    def __init__(self, **kwargs):        for k,v in kwargs.items():            self.__setattr__(k,v) # Sets each named attribute to their given value.        Container.configs.append(self)# Initializing some objects.Container(    Name="Test-Object1",    Property1="Something",    Property2="Something2",    Property3="Something3", )Container(    Name="Test-Object2",    Property1="Something",    Property2="Something2",    Property3="Something3", )Container(    Name="Test-Object2",    Property1="Something Completely different",    Property2="Something Completely different2",    Property3="Something Completely different3", )config = configparser.ConfigParser()for item in Container.configs: # Loops through all the created objects.    config[item.Name] = item.__dict__ # Adds all variables set on the object, using "Name" as the key.with open("example.ini", "w") as ConfigFile:    config.write(ConfigFile)在上面的示例中,我创建了三个包含要由 configparser 设置的变量的对象。但是,第三个对象Name与第二个对象共享变量。这意味着第三个将在写入 .ini 文件时“覆盖”第二个。例子.ini :[Test-Object1]name = Test-Object1property1 = Somethingproperty2 = Something2property3 = Something3[Test-Object2]name = Test-Object2property1 = Something Completely differentproperty2 = Something Completely different2property3 = Something Completely different3

杨魅力

到目前为止,其他答案忽略了希望代码执行以下操作的问题:为字典 a 中的值更改 b 中字典中的键我推断 中b没有替换键的任何数据a都应该单独保留。因此,遍历a创建新字典的键是c行不通的。我们需要b直接修改。一个有趣的方法是通过pop()我们通常与列表关联但也适用于字典的方法:a = {'a': 'A', 'b': 'B'}b = {'a': 123, 'b': 124, 'C': 125}for key in list(b):  # need a *copy* of old keys in b    if key in a:        b[a[key]] = b.pop(key)  # copy data to new key, remove old keyprint(b)输出> python3 test.py{'C': 125, 'A': 123, 'B': 124}>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python