program story

딕셔너리 목록을 단일 딕셔너리로 ​​병합하는 방법은 무엇입니까?

inputbox 2020. 9. 7. 08:06
반응형

딕셔너리 목록을 단일 딕셔너리로 ​​병합하는 방법은 무엇입니까?


이 같은 사전 목록을 어떻게 바꿀 수 있습니까?

[{'a':1}, {'b':2}, {'c':1}, {'d':2}]

이와 같은 단일 딕셔너리로

{'a':1, 'b':2, 'c':1, 'd':2}

이것은 모든 길이의 사전에서 작동합니다.

>>> result = {}
>>> for d in L:
...    result.update(d)
... 
>>> result
{'a':1,'c':1,'b':2,'d':2}

A와 이해 :

# Python >= 2.7
{k: v for d in L for k, v in d.items()}

# Python < 2.7
dict(pair for d in L for pair in d.items())

Python 3.3+의 경우 ChainMap컬렉션이 있습니다 .

>>> from collections import ChainMap
>>> a = [{'a':1},{'b':2},{'c':1},{'d':2}]
>>> dict(ChainMap(*a))
{'b': 2, 'c': 1, 'a': 1, 'd': 2}

참조 :


>>> L=[{'a': 1}, {'b': 2}, {'c': 1}, {'d': 2}]    
>>> dict(i.items()[0] for i in L)
{'a': 1, 'c': 1, 'b': 2, 'd': 2}

참고 : 'b'와 'c'의 순서는 dict가 순서가 지정되지 않았기 때문에 출력과 일치하지 않습니다.

사전에 둘 이상의 키 / 값이있을 수있는 경우

>>> dict(j for i in L for j in i.items())

플랫 사전의 경우 다음을 수행 할 수 있습니다.

from functools import reduce
reduce(lambda a, b: dict(a, **b), list_of_dicts)

이것은 @delnan과 비슷하지만 k / v (키 / 값) 항목을 수정하는 옵션을 제공하며 더 읽기 쉽다고 생각합니다.

new_dict = {k:v for list_item in list_of_dicts for (k,v) in list_item.items()}

예를 들어 다음과 같이 k / v elems를 바꿉니다.

new_dict = {str(k).replace(" ","_"):v for list_item in list_of_dicts for (k,v) in list_item.items()}

목록에서 dict 객체를 가져온 후 사전 .items () 생성기에서 k, v 튜플을 압축 해제합니다.


dict1.update( dict2 )

This is asymmetrical because you need to choose what to do with duplicate keys; in this case, dict2 will overwrite dict1. Exchange them for the other way.

EDIT: Ah, sorry, didn't see that.

It is possible to do this in a single expression:

>>> from itertools import chain
>>> dict( chain( *map( dict.items, theDicts ) ) )
{'a': 1, 'c': 1, 'b': 2, 'd': 2}

No credit to me for this last!

However, I'd argue that it might be more Pythonic (explicit > implicit, flat > nested ) to do this with a simple for loop. YMMV.


You can use join function from funcy library:

from funcy import join
join(list_of_dicts)

>>> dictlist = [{'a':1},{'b':2},{'c':1},{'d':2, 'e':3}]
>>> dict(kv for d in dictlist for kv in d.iteritems())
{'a': 1, 'c': 1, 'b': 2, 'e': 3, 'd': 2}
>>>

Note I added a second key/value pair to the last dictionary to show it works with multiple entries. Also keys from dicts later in the list will overwrite the same key from an earlier dict.


dic1 = {'Maria':12, 'Paco':22, 'Jose':23} dic2 = {'Patricia':25, 'Marcos':22 'Tomas':36}

dic2 = dict(dic1.items() + dic2.items())

and this will be the outcome:

dic2 {'Jose': 23, 'Marcos': 22, 'Patricia': 25, 'Tomas': 36, 'Paco': 22, 'Maria': 12}

참고URL : https://stackoverflow.com/questions/3494906/how-do-i-merge-a-list-of-dicts-into-a-single-dict

반응형