[英]Is there a simpler way to assign a dictionary and loop through to update?
Tried to just loop through each key appending it to a list, then loop through it, but it failed.试图循环遍历每个将其附加到列表的键,然后循环遍历它,但失败了。 Was wondering if there was a nicer way of updating my dictionary instead of defining all those variables above and updating it one-by-one?
想知道是否有更好的方法来更新我的字典,而不是定义上面的所有变量并逐个更新?
nfl = dict()
nfl['Tom'] = tom = dict()
nfl['bob'] = bob = dict()
nfl['kara'] = kara = dict()
nfl['Mike'] = mike = dict()
for k in data:
if 'tom_score' in data[k]:
<doing stuff here>
elif 'bob'in k:
bob.update(data[k])
elif 'kara'in k:
kara.update(data[k])
elif 'mike'in k:
mike.update(data[k])
Assuming it's a typo and 'Tom'
and 'tom_score'
supposed to be the same, you can use defaultdict
.假设这是一个错字,并且
'Tom'
和'tom_score'
应该是相同的,您可以使用defaultdict
。
from collections import defaultdict
nfl = defaultdict(dict)
for k in data:
if k in ['Tom', 'bob', 'kara', 'Mike']:
nfl[k].update(data[k])
You can skip if
part with names check if you want to have all names from the data
and not only specified ones.您可以跳过
if
part with names 检查是否要从data
获得所有名称,而不仅仅是指定的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.