3 回答
TA贡献1802条经验 获得超5个赞
由于configParser在大多数情况下都像 dict 一样,我们在这里可以做的是使用key不同的代码块来确保有唯一的块。
这是一个简单的测试来展示它的实际效果:
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)
在上面的示例中,我创建了三个包含要由 configparser 设置的变量的对象。但是,第三个对象Name与第二个对象共享变量。这意味着第三个将在写入 .ini 文件时“覆盖”第二个。
例子.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贡献1811条经验 获得超6个赞
到目前为止,其他答案忽略了希望代码执行以下操作的问题:
为字典 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 key
print(b)
输出
> python3 test.py
{'C': 125, 'A': 123, 'B': 124}
>
添加回答
举报
