3 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
{a[k] if k in a else k: v for k, v in b.items()}

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
由于configParser在大多數(shù)情況下都像 dict 一樣,我們?cè)谶@里可以做的是使用key不同的代碼塊來確保有唯一的塊。
這是一個(gè)簡(jiǎn)單的測(cè)試來展示它的實(shí)際效果:
import configparser
class 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)
在上面的示例中,我創(chuàng)建了三個(gè)包含要由 configparser 設(shè)置的變量的對(duì)象。但是,第三個(gè)對(duì)象Name與第二個(gè)對(duì)象共享變量。這意味著第三個(gè)將在寫入 .ini 文件時(shí)“覆蓋”第二個(gè)。
例子.ini :
[Test-Object1]
name = Test-Object1
property1 = Something
property2 = Something2
property3 = Something3
[Test-Object2]
name = Test-Object2
property1 = Something Completely different
property2 = Something Completely different2
property3 = Something Completely different3

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
到目前為止,其他答案忽略了希望代碼執(zhí)行以下操作的問題:
為字典 a 中的值更改 b 中字典中的鍵
我推斷 中b沒有替換鍵的任何數(shù)據(jù)a都應(yīng)該單獨(dú)保留。因此,遍歷a創(chuàng)建新字典的鍵是c行不通的。我們需要b直接修改。一個(gè)有趣的方法是通過pop()我們通常與列表關(guān)聯(lián)但也適用于字典的方法:
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 key
print(b)
輸出
> python3 test.py
{'C': 125, 'A': 123, 'B': 124}
>
添加回答
舉報(bào)