我有一个单键词典列表。例如:
lst = [
{'1': 'A'},
{'2': 'B'},
{'3': 'C'}
]
我想简单地将其转换为普通词典:
dictionary = {
'1': 'A',
'2': 'B',
'3': 'C'
}
最简洁/有效的方法是什么?
答案 0 :(得分:13)
您可以使用reduce:
reduce(lambda r, d: r.update(d) or r, lst, {})
演示:
>>> lst = [
... {'1': 'A'},
... {'2': 'B'},
... {'3': 'C'}
... ]
>>> reduce(lambda r, d: r.update(d) or r, lst, {})
{'1': 'A', '3': 'C', '2': 'B'}
或者您可以链接项目调用(Python 2):
from itertools import chain, imap
from operator import methodcaller
dict(chain.from_iterable(imap(methodcaller('iteritems'), lst)))
Python 3版本:
from itertools import chain
from operator import methodcaller
dict(chain.from_iterable(map(methodcaller('items'), lst)))
演示:
>>> from itertools import chain, imap
>>> from operator import methodcaller
>>>
>>> dict(chain.from_iterable(map(methodcaller('iteritems'), lst)))
{'1': 'A', '3': 'C', '2': 'B'}
或者使用词典理解:
{k: v for d in lst for k, v in d.iteritems()}
演示:
>>> {k: v for d in lst for k, v in d.iteritems()}
{'1': 'A', '3': 'C', '2': 'B'}
在这三个中,对于简单的3字典输入,字典理解最快:
>>> import timeit
>>> def d_reduce(lst):
... reduce(lambda r, d: r.update(d) or r, lst, {})
...
>>> def d_chain(lst):
... dict(chain.from_iterable(imap(methodcaller('iteritems'), lst)))
...
>>> def d_comp(lst):
... {k: v for d in lst for k, v in d.iteritems()}
...
>>> timeit.timeit('f(lst)', 'from __main__ import lst, d_reduce as f')
2.4552760124206543
>>> timeit.timeit('f(lst)', 'from __main__ import lst, d_chain as f')
3.9764280319213867
>>> timeit.timeit('f(lst)', 'from __main__ import lst, d_comp as f')
1.8335261344909668
当将输入列表中的项目数量增加到1000时,chain
方法会赶上:
>>> import string, random
>>> lst = [{random.choice(string.printable): random.randrange(100)} for _ in range(1000)]
>>> timeit.timeit('f(lst)', 'from __main__ import lst, d_reduce as f', number=10000)
5.420135974884033
>>> timeit.timeit('f(lst)', 'from __main__ import lst, d_chain as f', number=10000)
3.464245080947876
>>> timeit.timeit('f(lst)', 'from __main__ import lst, d_comp as f', number=10000)
3.877490997314453
从此处开始,进一步增加输入列表似乎无关紧要; chain()
方法的速度提高了一小部分,但从未获得明显的优势。
答案 1 :(得分:8)
您可以使用dictionary comprehension:
>>> lst = [
... {'1': 'A'},
... {'2': 'B'},
... {'3': 'C'}
... ]
>>> {k:v for x in lst for k,v in x.items()}
{'2': 'B', '3': 'C', '1': 'A'}
>>>
答案 2 :(得分:1)
answer = {}
for d in L:
answer.update(d)
<强>输出强>:
>>> L = [
... {'1': 'A'},
... {'2': 'B'},
... {'3': 'C'}
... ]
>>> answer = {}
>>> for d in L: answer.update(d)
...
>>> answer
{'2': 'B', '3': 'C', '1': 'A'}
OR
answer = {k:v for d in L for k,v in d.items()}