简体   繁体   English

有没有更简单的方法来分配字典并循环更新?

[英]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.

相关问题 有没有一种更Python化的方式可以遍历列表,然后让每个循环变量更新字典? - Is there a more Pythonic way to loop through a list and then have each loop variable update a dictionary? 有没有办法遍历一个列表,并分配一个变量 - Is there a way to loop through a list, and assign a variable 创建与列表关联的字典,并通过循环对其进行更新 - Create a dictionary that is associated with lists and update this through a loop 创建单独变量字典的更简单方法? - Simpler way to create dictionary of separate variables? 在python中遍历复杂字典的更简单方法? - Simpler way to traverse complex dictionary in python? 从字典中获取数据的更简单方法 - simpler way for getting data from dictionary 遍历名称列表以提取文件并分配给 Python 中的字典 - loop through a list of names to pull files and assign to a dictionary in Python 如何遍历txt文件并在Python中为字典分配值? - How to loop through txt file and assign values to dictionary in Python? 如何遍历字典并根据键为变量赋值? - How to loop through a dictionary and assign values to a variable based on keys? 如何遍历 JSON 中的值并分配给另一个字典 - How to loop through values in JSON and assign to another dictionary
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM