我在Python中有一个包含only one
键值对的字典结构。键是一个元组,值是一个元组列表。示例:{(element1, element2): [(element1.1, element2.1), (element1.2, element2.2).....]}
我试图通过这个字典迭代,以获得关键,然后是值。然后我想构造另一个字典,它将包含:
{ element1: element2
element1.1: element2.1
element1.2: element2.2 }
我试过的是:
field_dictionary is the dictionary that I previously described.
for (k,v), l in field_dictionary:
log_dictionary[k] = v
for (element1, element2) in l:
log_dictionary[element1] = element2
我得到的是一个错误:
for (k,v), l in field_dictionary:
ValueError: too many values to unpack, expected 2
有人能帮我一下吗?from itertools import chain
spam = {('element1', 'element2'): [('element1.1', 'element2.1'), ('element1.2', 'element2.2')]}
key, value = list(spam.items())[0]
eggs = dict(chain((key,), value))
print(eggs)
输出:
{'element1': 'element2', 'element1.1': 'element2.1', 'element1.2': 'element2.2'}
或者
for key, value in spam.items():
eggs = dict(chain((key, ), value))
print(eggs)
相同的输出