确保列表中的所有列表都具有相同的键 [英] Make sure all dicts in a list have the same keys

查看:107
本文介绍了确保列表中的所有列表都具有相同的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含字典的列表,如

  [{'x':42},{'x':23, 'y':5}] 

,并希望确保所有的dicts都有相同的键,的如果密钥不存在于原始的dict中。所以上面的列表应该成为

  [{'x':42,'y':无},{'x' 23,'y':5}] 

这是最美丽和最有魅力的方法?当前方法:

  keys = reduce(lambda k,l:k.union(set(l)),[d.keys (ld(my_list))] 
对于i,l在枚举中(my_list)(my_list)中的()for d in my_list],set())
new_list = [dict.fromkeys ):
new_list [i] .update(l)

但特别是前两行看起来很笨拙。想法?

解决方案

 >>>来自itertools import chain 
>>>> l = [{'x':42},{'x':23,'y':5}]
>>> all_keys = set(chain.from_iterable(l))
>>> for d in l:
d.update((k,None)for all in allkeys-d.viewkeys())


>>> l
[{'y':None,'x':42},{'y':5,'x':23}]


I have a list with dictionaries like

[{'x': 42}, {'x': 23, 'y': 5}]

and want to make sure all dicts have the same keys, with values of None if the key was not present in the original dict. So the list above should become

[{'x': 42, 'y': None}, {'x': 23, 'y': 5}]

What's the most beautiful and pythonic way to do this? Current approach:

keys = reduce(lambda k, l: k.union(set(l)), [d.keys() for d in my_list], set())
new_list = [dict.fromkeys(keys, None) for i in xrange(len(my_list))]
for i, l in enumerate(my_list):
    new_list[i].update(l)

But especially the first two lines seem kind of clumsy. Ideas?

解决方案

>>> from itertools import chain 
>>> l = [{'x': 42}, {'x': 23, 'y': 5}]
>>> all_keys = set(chain.from_iterable(l))   
>>> for d in l:
        d.update((k,None) for k in all_keys-d.viewkeys())


>>> l
[{'y': None, 'x': 42}, {'y': 5, 'x': 23}]

这篇关于确保列表中的所有列表都具有相同的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆