我有一个字典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,4,1,4,7,3,6,0,2,3,3,13,9}
注意:我还没有接触过熊猫,我更喜欢帮助而不是使用它们:)总有一天我会接触到它们的。
发布于 2016-08-30 22:43:04
一般情况下,使用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]}发布于 2016-08-30 22:37:42
dict_shepherd = {'shepherd': []}
for name in dict1:
dict_shepherd['shepherd'].append(dict1['shepherd'])值得注意的是,标准字典不强制对其内容进行任何排序,因此循环遍历这些项可能不会以与示例中列出的顺序相同的顺序生成它们。
发布于 2016-08-30 22:45:24
您还可以使用字典和列表理解在一行中获取所有列表:
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没有顺序。
https://stackoverflow.com/questions/39230401
复制相似问题