在一个字典上循环生成多个字典

2024-04-24 03:41:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,dict1,我想找到一种方法来循环遍历它,以分离出牧羊人、牧羊犬和贵宾犬的所有值。如果我的语法不正确,我很抱歉。我还在学字典呢!你知道吗

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
 }
}

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

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

注:我还没有接触过熊猫基地,更喜欢不用它们的帮助:)总有一天我会找到它们的。你知道吗


Tags: 方法字典语法基地dictvsbobann
3条回答

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

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没有顺序。你知道吗

在一般情况下,对于具有^{}的子目录中数量可变的键,可以求解它:

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]}
dict_shepherd = {'shepherd': []}
for name in dict1:
    dict_shepherd['shepherd'].append(dict1['shepherd'])

值得注意的是,标准词典不强制对其内容进行任何排序,因此循环遍历这些项可能不会产生与示例中列出的顺序相同的顺序。你知道吗

相关问题 更多 >