从Key of Dictionary中获取另一个字典中的键值

时间:2018-05-28 09:36:36

标签: python list-comprehension dictionary-comprehension

这是我的字典列表。

d = [{'count': '100', 'zone': 'PIMPRI', 'cycle': '15'},
     {'count': '50', 'zone': 'PIMPRI', 'cycle': '15'},
     {'count': '150', 'zone': 'PIMPRI', 'cycle': '30'}]

如何获得如下输出:

d_one = [{'count': '100', 'zone': 'PIMPRI', 'cycle': '15'},
         {'count': '50', 'zone': 'PIMPRI', 'cycle': '15'}]

d_two = [{'count': '150', 'zone': 'PIMPRI', 'cycle': '30'}]

从两个键区和循环中获取字典列表中的不同数据。对于相同的区域和周期对,创建一个字典列表,直到结束。

5 个答案:

答案 0 :(得分:1)

使用对(dct['zone'], dct['cycle'])作为键来制作一个词典:

>>> result = {}
>>> 
>>> for dct in d:
...     result.setdefault((dct['zone'], dct['cycle']), []).append(dct)
... 
>>> result
{('PIMPRI', '15'): [{'count': '100', 'zone': 'PIMPRI', 'cycle': '15'}, {'count': '50', 'zone': 'PIMPRI', 'cycle': '15'}], ('PIMPRI', '30'): [{'count': '150', 'zone': 'PIMPRI', 'cycle': '30'}]}

答案 1 :(得分:0)

您想要filter您的数据:

d_one = filter(lambda d:d['cycle']=='15',d)
> [{'count': '100', 'zone': 'PIMPRI', 'cycle': '15'}, 
>  {'count': '50', 'zone': 'PIMPRI', 'cycle': '15'}]

d_two = filter(lambda d:d['cycle']=='30',d)
> [{'count': '150', 'zone': 'PIMPRI', 'cycle': '30'}]

答案 2 :(得分:0)

一种方法是使用集合。并将变量('cycle')作为词典中的关键字。

例如:

import collections 
res = collections.defaultdict(list)
d = [{'count': '100', 'zone': 'PIMPRI', 'cycle': '15'},
     {'count': '50', 'zone': 'PIMPRI', 'cycle': '15'},
     {'count': '150', 'zone': 'PIMPRI', 'cycle': '30'}]

for i in d:
    res[i["cycle"]].append(i)
print(res['15'])
print("-----")
print(res['30'])

<强>输出:

[{'count': '100', 'zone': 'PIMPRI', 'cycle': '15'}, {'count': '50', 'zone': 'PIMPRI', 'cycle': '15'}]
-----
[{'count': '150', 'zone': 'PIMPRI', 'cycle': '30'}]

答案 3 :(得分:0)

尝试groupby

from itertools import groupby 
from operator import itemgetter
grouper = itemgetter("cycle", "zone")
dict_one,dict_two = (list(g) for _,g in groupby(d,key=grouper))

代码将返回一个元组,现在我们只有2个元素。因此,值赋值将在此处起作用。如果您有更多值,则可以将这些值分配给dict或存储为可迭代。

<强>输出

In [9]: dict_one
Out[9]: 
[{'count': '100', 'cycle': '15', 'zone': 'PIMPRI'},
 {'count': '50', 'cycle': '15', 'zone': 'PIMPRI'}]

In [10]: dict_two
Out[10]: [{'count': '150', 'cycle': '30', 'zone': 'PIMPRI'}]

答案 4 :(得分:0)

为什么要为所有这些值使用单独的词典。难道你不能把它变成一本字典。对于你的例子,

d = [{'count': '100', 'zone': 'PIMPRI', 'cycle': '15'},
     {'count': '50', 'zone': 'PIMPRI', 'cycle': '15'},
     {'count': '150', 'zone': 'PIMPRI', 'cycle': '30'}]

这是我们可以得到的,

res = {}
for ele in d:
    res.setdefault((ele['cycle'],ele['zone']), [])
    res[(ele['cycle'], ele['zone'])].append(ele['count'])