将单键词典列表转换为单个词典 [英] Convert list of single key dictionaries into a single dictionary
问题描述
我有一个单键词典列表.例如:
I have a list of single-key dictionaries. For example:
lst = [
{'1': 'A'},
{'2': 'B'},
{'3': 'C'}
]
我想简单地将其转换为普通词典:
I'd like to simply convert this into a normal dictionary:
dictionary = {
'1': 'A',
'2': 'B',
'3': 'C'
}
最简洁/最有效的方法是什么?
What's the most concise/efficient way to do this?
推荐答案
您可以使用reduce:
You can use 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):
or you could chain the items calls (Python 2):
from itertools import chain, imap
from operator import methodcaller
dict(chain.from_iterable(imap(methodcaller('iteritems'), lst)))
Python 3版本:
Python 3 version:
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字典输入,对dict的理解最快:
Of the three, for the simple 3-dictionary input, the dict comprehension is fastest:
>>> 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
方法会赶上:
When you increase the number of items in the inputlist to 1000, then the chain
method catches up:
>>> 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()
方法快了一个很小的百分比,但从未获得明显的优势.
Increasing the input list further doesn't appear to matter from here on out; the chain()
approach is a small percentage faster but never gains a clear advantage.
这篇关于将单键词典列表转换为单个词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!