如何在一个值不同的字典列表中选择一个字典?

时间:2016-06-28 09:53:50

标签: python dictionary

我有一个这样的词典列表:

xyz =[ {"key1":"1","key2":"2","key3":"x_1"},{"key1":"1","key2":"2","key3":"x_2"},{"key1":"1","key2":"2","key3":"x_3"},{"key1":"5","key2":"6","key3":"y_1"},{"key1":"5","key2":"6","key3":"y_2"},{"key1":"5","key2":"6","key3":"y_3"}]

我正在尝试为每个唯一的'key1'值选择第一个dict。对于上面的字典,我期待输出为:

 xyz=[{"key1":"1","key2":"2","key3":"x_1"},{"key1":"5","key2":"6","key3":"y_1"},]

我尝试了以下代码:

dictout = [dict(sample) for sample in set(tuple(item.items()) for item in xyz)]

但我最终得到了:

[{'key3': 'x_1', 'key2': '2', 'key1': '1'}, {'key3': 'x_3', 'key2': '2', 'key1': '1'}, {'key3': 'y_2', 'key2': '6', 'key1': '5'}, {'key3': 'x_2', 'key2': '2', 'key1': '1'}, {'key3': 'y_1', 'key2': '6', 'key1': '5'}, {'key3': 'y_3', 'key2': '6', 'key1': '5'}]

我无法根据“key1”的值构建唯一的dicts。

如果有人给我一个接近的想法,那就太好了。

谢谢。

1 个答案:

答案 0 :(得分:3)

您可以使用groupby库中的itertools

import itertools

xyz =[ {"key1":"1","key2":"2","key3":"x_1"},{"key1":"1","key2":"2","key3":"x_2"},
       {"key1":"1","key2":"2","key3":"x_3"},{"key1":"5","key2":"6","key3":"y_1"},
       {"key1":"5","key2":"6","key3":"y_2"},{"key1":"5","key2":"6","key3":"y_3"}]

result = []
for key, value in itertools.groupby(xyz, lambda x: x["key1"]):
    result.append(list(value))

print([x[0] for x in result])

输出:

[{'key1': '1', 'key2': '2', 'key3': 'x_1'}, {'key1': '5', 'key2': '6', 'key3': 'y_1'}]

甚至列表理解:

result = [list(value) for key, value in itertools.groupby(xyz, lambda x: x["key1"])]

您还可以使用itemgetter库中的operator

import operator
import itertools

result = [list(value) for key, value in itertools.groupby(xyz, operator.itemgetter("key1")]

您也可以使用其他词典:

d = {}
for key, value in itertools.groupby(xyz, lambda x: x["key1"]):
    d[key] = list(value)

print([value[0] for key, value in sorted(d.items())])