在Python中创建唯一键的列表
我有一份清单在Python中创建唯一键的列表,python,python-2.7,Python,Python 2.7,我有一份清单 [{"1":"value"},{"1":"second_value"},{"2":"third_value"},{"2":"fourth_value"},{"3":"fifth_value"}] 要将其转换为 [{"1":"value","2":"third_value","3":"fifth_value"},{"1":"second_value","2":"fourth_value"}] 您可以使用集合。defaultdict: >>> import col
[{"1":"value"},{"1":"second_value"},{"2":"third_value"},{"2":"fourth_value"},{"3":"fifth_value"}]
要将其转换为
[{"1":"value","2":"third_value","3":"fifth_value"},{"1":"second_value","2":"fourth_value"}]
您可以使用集合。defaultdict:
>>> import collections
>>> result = collections.defaultdict(list)
>>> for item in d:
... result[item.values()[0]].append(item.keys()[0])
...
>>> [{key: value for key in keys} for value, keys in result.items()]
[{'1': 'second_value', '2': 'second_value'}, {'1': 'value', '3': 'value', '2': 'value'}]
请注意,
second\u value
位于value
之前,因为排序是任意的(除非您明确指定value
应在second\u value
之前排序,否则上面将给出字典返回的顺序).您可以在此处使用collections.defaultdict
。迭代列表,将值用作键,并收集与列表中某个值相关的所有键
>>> from collections import defaultdict
>>> d = defaultdict(list)
for dic in lis:
for k, v in dic.items():
d[v].append(k)
...
现在d
变成:
>>> d
defaultdict(<type 'list'>,
{'second_value': ['1', '2'],
'value': ['1', '2', '3']})
可能有一种更干净的方法可以做到这一点,请注意:
d = [{"1":"value"},{"1":"second_value"},{"2":"third_value"},{"2":"fourth_value"},{"3":"fifth_value"}]
results = [{}]
for item in stuff:
j,k = item.items()[0] // Do the initial dicts always contain one key-value pair?
for result in results:
if j not in result:
result[j] = k
break
if result == results[-1]:
results.append(item)
break
结果:
[{'1': 'value', '3': 'fifth_value', '2': 'third_value'}, {'1': 'second_value', '2': 'fourth_value'}]
到目前为止你有什么?@SimeonVisser正在制作一个新的列表,检查它是否包含键。它是否仅限于“值”和“第二个值”?@Jordonias它不能有任何值,但我必须对列表中每个唯一的键集进行记录假设列表包含所有不同的values@Arpit在问题正文中发布一个示例。假设列表包含所有不同的values@Arpit太好了,你把问题的意思改成了完全不同的意思。
[{'1': 'value', '3': 'fifth_value', '2': 'third_value'}, {'1': 'second_value', '2': 'fourth_value'}]