我想创建一个包含多个键和值的字典。在这一点上,我不确定我是否正确地提出了我的问题。但这是我想要创建的一个例子:
patDct = {
'mkey1':{'key1':'val_a1', 'key2':'val_a2', 'key3':'val_a3'},
'mkey2':{'key1':'val_b1', 'key2':'val_b2', 'key3':'val_b3'},
....
}
我有两个词典,我正在为他们提取'mkey *'和'val *'的信息。 'key *'是字符串。
我有一段代码来创建没有'mkey *'的字典,但是只打印出最后一组值。以下就是我现在所拥有的。 “storedct”和“datadct”是两个给定的词典。 在这里,我希望'mkey *'获得“item”的值。
patDct = dict()
for item in storedct :
for pattern in datadct :
if pattern in item :
patDct['key1'] = datadct[pattern]["dpath"]
patDct['key2'] = datadct[pattern]["mask"]
patDct['key3'] = storedct[item]
感谢您的任何建议。
答案 0 :(得分:1)
patDct = dict()
n=1
for item in storedct :
patDct["mkey%s"%n] = {}
p = patDct["mkey%s"%n]
for pattern in datadct :
if pattern in item :
p['key1'] = datadct[pattern]["dpath"]
p['key2'] = datadct[pattern]["mask"]
p['key3'] = storedct[item]
n +=1
print patDct
答案 1 :(得分:1)
根据我对您的代码的理解,我想:
patDct = dict()
i = 0
for item in storedct :
for pattern in datadct :
if pattern in item :
i = i + 1
new_item = {}
new_item['key1'] = datadct[pattern]["dpath"]
new_item['key2'] = datadct[pattern]["mask"]
new_item['key3'] = storedct[item]
# I used a counter to generate the `mkey` values,
# not sure you want it that way
patDct['mkey{0}'.format(i)] = new_item
离你的需求不远......