循环在字典上制作多个词典

时间:2016-08-30 14:34:45

标签: python dictionary

我有一个字典,dict1,我想找到一种方法来循环它,以隔离牧羊人,牧羊犬和贵宾犬的所有价值观。如果我的语法关闭,我道歉时间。我还在学习字典!

barplot(df$Amount, names.arg = df$Name)

这就是我想要的,例如,但是能够循环为每只狗制作一本字典:

dict_shepherd = {'shepherd':1,3,3,3,4,1,4,7,3,6,0,2,3,3,13,9}

注意:我还没有接触过大熊猫的基础,并且不使用它们而更喜欢帮助:)我会在一天之内找到它们。

4 个答案:

答案 0 :(得分:2)

dict_shepherd = {'shepherd': []}
for name in dict1:
    dict_shepherd['shepherd'].append(dict1['shepherd'])

值得注意的是,标准词典不会强制执行其内容的任何排序,因此循环浏览这些项目可能不会按照您的示例中列出的顺序生成它们。

答案 1 :(得分:2)

一般情况下,您可以使用defaultdict(list)在子代码中为可变数量的键解决此问题:

from collections import defaultdict
from pprint import pprint

dict1 = # your dictionary of dictionaries here, removed to shorten the presented code

d = defaultdict(list)
for sub_dict in dict1.values():
    for key, value in sub_dict.items():
        d[key].append(value)

pprint(dict(d))

哪会产生:

{'collie': [2, 7, 8, 5, 2, 6, 5, 2, 2, 2, 2, 8, 9, 2, 2, 7],
 'poodle': [2, 2, 1, 8, 2, 3, 8, 5, 4, 1, 2, 2, 2, 4, 4, 2],
 'shepherd': [3, 9, 4, 1, 3, 4, 1, 6, 3, 3, 3, 2, 7, 0, 13, 3]}

答案 2 :(得分:2)

您还可以使用字典和列表推导在一行中获取所有列表:

ds = {type: [val[type] for val in dict1.values()] for type in ['shepherd', 'collie', 'poodle']}

# {'collie': [2, 7, 8, 5, 2, 6, 5, 2, 2, 2, 2, 8, 9, 2, 2, 7],
#  'poodle': [2, 2, 1, 8, 2, 3, 8, 5, 4, 1, 2, 2, 2, 4, 4, 2],
#  'shepherd': [3, 9, 4, 1, 3, 4, 1, 6, 3, 3, 3, 2, 7, 0, 13, 3]}

但是,列表没有特别的顺序,因为dict没有订单。

答案 3 :(得分:1)

您可以按照以下用户使用defaultdict

from collections import defaultdict

dict1 = {'Bob VS Sarah': {'shepherd': 1,'collie': 5,'poodle': 8},
 'Bob VS Ann': {'shepherd': 3,'collie': 2,'poodle': 1},
 'Bob VS Jen': {'shepherd': 3,'collie': 2,'poodle': 2},
 'Sarah VS Bob': {'shepherd': 3,'collie': 2,'poodle': 4},
 'Sarah VS Ann': {'shepherd': 4,'collie': 6,'poodle': 3},
 'Sarah VS Jen': {'shepherd': 1,'collie': 5,'poodle': 8},
 'Jen VS Bob': {'shepherd': 4,'collie': 8,'poodle': 1},
 'Jen VS Sarah': {'shepherd': 7,'collie': 9,'poodle': 2},
 'Jen VS Ann': {'shepherd': 3,'collie': 7,'poodle': 2},
 'Ann VS Bob': {'shepherd': 6,'collie': 2,'poodle': 5},
 'Ann VS Sarah': {'shepherd': 0,'collie': 2,'poodle': 4},
 'Ann VS Jen': {'shepherd': 2,'collie': 8,'poodle': 2},
 'Bob VS Bob': {'shepherd': 3,'collie': 2,'poodle': 2},
 'Sarah VS Sarah': {'shepherd': 3,'collie': 2,'poodle': 2},
 'Ann VS Ann': {'shepherd': 13,'collie': 2,'poodle': 4},
 'Jen VS Jen': {'shepherd': 9,'collie': 7,'poodle': 2}}


def iter_dict(dict_, result=defaultdict(list)): # mutable as default value ot reuse result over the recursion
    for k, v in dict_.items():
        if isinstance(v, dict):
            iter_dict(v)
        else:
            result[k].append(v)
    return result

print(iter_dict(dict1))

这会产生一个包含所有预期结果的词典

defaultdict(<class 'list'>, {'shepherd': [3, 4, 9, 2, 3, 1, 0, 4, 1, 6, 3, 3, 13, 3, 3, 7], 'collie': [2, 8, 7, 8, 7, 5, 2, 6, 5, 2, 2, 2, 2, 2, 2, 9], 'poodle': [1, 1, 2, 2, 2, 8, 4, 3, 8, 5, 2, 2, 4, 2, 4, 2]})