我正在编写一个函数来将字典列表转换为字典词典。我发现Find the index of a dict within a list, by matching the dict's value之后有一个更好的解决方案,因为它通过添加索引项而不是从dicts中提取来处理潜在的重复值。
然而,在测试中我发现该功能改变了原始列表,即使我正在制作一个明确的副本。如果我试图重新运行功能,这是显而易见的,但我不明白为什么。
def lod2dict(iterable,target="name"):
'''Turn a list of dictionaries into a dict of dicts.
If a dict does not have the target key, that element is skipped.'''
d = {}
copy = list(iterable)
# N.B. It makes no difference whether I use this or
#copy = list[:]
# or
#copy = [x for x in iterable]
for item in copy:
try:
newkey=item[target]
item.pop(target)
d[newkey] = item
except KeyError:
print("Failure for", item)
pass
return d
这是一个用小字典显示破坏性影响的游戏。
testcase = {"heroes": [
{"name": "Batman", "home": "Wayne Manor", "weapon": "Batarang (TM)"},
{"name": "Spider-Man", "home": "Queens", "weapon": "Sarcasm"},
{"name": "Deadpool", "home": "Good Question. Next?", "weapon": "Sarcasm and swords"},
{"name": "Wonder Woman", "home": "Themyscira", "weapon": "Lasso and sword"},
{"name": "Aquaman", "home": "The Oceans", "weapon": "trident"}
]}
In [4]: lod2dict(testcase['heroes'], 'name')
Out[4]:
{'Aquaman': {'home': 'The Oceans', 'weapon': 'trident'},
'Batman': {'home': 'Wayne Manor', 'weapon': 'Batarang (TM)'},
'Deadpool': {'home': 'Good Question. Next?', 'weapon': 'Sarcasm and swords'},
'Spider-Man': {'home': 'Queens', 'weapon': 'Sarcasm'},
'Wonder Woman': {'home': 'Themyscira', 'weapon': 'Lasso and sword'}}
In [5]: lod2dict(testcase['heroes'], 'name')
Failure for {'home': 'Wayne Manor', 'weapon': 'Batarang (TM)'}
Failure for {'home': 'Queens', 'weapon': 'Sarcasm'}
Failure for {'home': 'Good Question. Next?', 'weapon': 'Sarcasm and swords'}
Failure for {'home': 'Themyscira', 'weapon': 'Lasso and sword'}
Failure for {'home': 'The Oceans', 'weapon': 'trident'}
Out[5]: {}