Merge dictionaries in list python [duplicate] - python

This question already has an answer here:
Merging list of dicts in python
(1 answer)
Closed 2 years ago.
I have the a list of dicts in python in the following format:
dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]
I want to output something like this:
dict2 = {'a':20, 'b':10, 'c':15 }
How to do it? Thanks in advance!

Try with a dictionary comprehension:
dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]
dict2={dc['Name']:dc['value'] for dc in dict1}
Output:
dict2
{'a': 20, 'b': 10, 'c': 15}

I think you can do it with for loop efficiently. Check this:
dict1 = [{'Name':'a', 'value':20},{'Name':'b', 'value':10},{'Name':'c', 'value':15}]
dict2 = dict()
for a in range(len(dict1)):
dict2[dict1[a].get('Name')] = dict1[a].get('value')
print(dict2)
Output:
{'a': 20, 'b': 10, 'c': 15}

Related

How to create a list of dicts into a single dict with python? [duplicate]

This question already has answers here:
How do I merge a list of dicts into a single dict?
(11 answers)
How do I merge dictionaries together in Python?
(7 answers)
Closed 1 year ago.
I have a large list of dictionaries, each with exactly one entry and with unique keys, and I want to 'combine' them into a single dict with python 3.8.
So here is an example that actually works:
mylist = [{'a':1}, {'b':2}, {'c':3}]
mydict = {list(x.keys())[0]:list(x.values())[0] for x in mylist}
which gives as result the expected output:
{'a': 1, 'b': 2, 'c': 3}
But it looks ugly and not quite pythonic. Is there a better one-line solution to this problem?
This is similar to the question asked HERE, but in my example I am looking for an answer (1) to merge many dicts together and (2) for a one-line solution. That makes my question different from the question already asked.
mydict = { k:v for elt in mylist for k, v in elt.items()}
Try this out, simple and effective.
mylist = [{'a':1}, {'b':2}, {'c':3}]
result = {}
for d in mylist:
result.update(d)
Result
{'a': 1, 'b': 2, 'c': 3}

How can I merge multiple dictionaries and add the values of the same key? (Python) [duplicate]

This question already has answers here:
Sum corresponding elements of multiple python dictionaries
(4 answers)
Closed 2 years ago.
Suppose I have the following dictionaries:
dict1 = {'a': 10, 'b': 8, 'c':3}
dict2 = {'c': 4}
dict3 = {'e':9, 'a':3}
I'm trying to merge them in a way such that the new (combinational) dictionary contains all the keys and all the values of the same key are added together. For instance, in this case, my desired output looks like:
dict = {'a': 13, 'b': 8, 'c':7, 'e':9}
It looks like the update() method doesn't work since some values are overwritten. I also tried ChainMaps and encountered the same issue. How can I merge multiple dictionaries and add the values of the same key?Thanks a lot:)
Here's a dictionary comprehension to achieve this using itertools.chain.from_iterable() and sum(). Here, I am creating a set of keys from all the three dicts. Then I am iteration over this set inside dictionary comprehension to get the sum of values per key.
>>> from itertools import chain
>>> dict1 = {'a': 10, 'b': 8, 'c':3}
>>> dict2 = {'c': 4}
>>> dict3 = {'e':9, 'a':3}
>>> my_dicts = dict1, dict2, dict3
>>> {k: sum(dd.get(k, 0) for dd in my_dicts) for k in set(chain.from_iterable(d.keys() for d in my_dicts))}
{'a': 13, 'e': 9, 'b': 8, 'c': 7}
This code below should do the trick:
dict1 = {'a': 10, 'b': 8, 'c':3}
dict2 = {'c': 4}
dict3 = {'e':9, 'a':3}
multiple_dict = [dict1, dict2, dict3]
final_dict = {}
for dict in multiple_dict:
for key, value in dict.items():
if key in final_dict:
final_dict[key] += value
else:
final_dict[key] = value
print(final_dict)

Removing duplicate values in Python dictionaries? [duplicate]

This question already has answers here:
Removing Duplicates From Dictionary
(11 answers)
remove duplicates values in a dictionary python
(1 answer)
Closed 2 years ago.
More a concept question than a direct coding one. But say I had a dictionary akin to this one.
Dict = {'A':1, 'B':3, 'C':3, 'D':4, 'E':1}
Dict2 = {}
And I wanted to take all instances were two keys had the same value, and put them in a different dictionary, what sort of process be the most efficient? I've tried measures like
for value in Dict.items()
for a in value:
if a != b:
continue
else:
Dict2.append(a)
continue
But to no luck.
You can do something like this:
Dict = {'A':1, 'B':3, 'C':3, 'D':4, 'E':1}
result = {}
for k, v in Dict.items():
result.setdefault(v, set()).add(k)
print("Original: ")
print(Dict)
print("------------")
print("Result: ")
print(result)
Original:
{'A': 1, 'B': 3, 'C': 3, 'D': 4, 'E': 1}
Result:
{1: {'A', 'E'}, 3: {'B', 'C'}, 4: {'D'}}
Old school, with regular loops. Could maybe be done with list or dict comprehensions, but this is easy and obvious:
dict = {'A':1, 'B':3, 'C':3, 'D':4, 'E':1}
# Make a reverse dictionary that maps values to lists of keys
# that have that value in the original dict
reverse_dict = {}
for k, v in dict.items():
reverse_dict.setdefault(v, list()).append(k)
# Show the reverse dict
# print(reverse_dict)
# Move entries for keys that had duplicates from the original
# dict to a new dict
dups_dict = {}
for k, vs in reverse_dict.items():
if len(vs) > 1: # if there was more than one key with this value
for v in vs: # for each of those keys
dups_dict[v] = k # copy it to the new dict
del dict[v] # and remove it from the original dict
# Show the original dict and the new one
print(dict)
print(dups_dict)
Result:
{'D': 4}
{'A': 1, 'E': 1, 'B': 3, 'C': 3}

Incorrect result after merge two dictionary in case when {str: dict} [duplicate]

This question already has answers here:
How to merge dictionaries of dictionaries?
(34 answers)
Closed 5 years ago.
I trying to merge 2 dictionaries which have the ability to create nested dictionaries and had an incorrect result.
Code example.
def merge_two_dicts(x, y):
z = x.copy()
z.update(y)
return z
def create_dict(l, val):
d = {}
for a in reversed(l):
if d == {}:
d = {a: val}
else:
d = {a: d}
return d
test = "a.b.t.q"
test2 = "a.b.t.w"
list1 = test.split(".")
list2 = test2.split(".")
val1 = "test"
val2 = "test2"
dict1 = create_dict(list1, val1)
dict2 = create_dict(list2, val2)
merged_dict = merge_two_dicts(dict1, dict2)
print "Dict #1"
print dict1
print "========================"
print "Dict #2"
print dict2
print "========================"
print "Merged dict"
print merged_dict
And the actual result is.
Dict #1
{'a': {'b': {'t': {'q': 'test'}}}}
========================
Dict #2
{'a': {'b': {'t': {'w': 'test2'}}}}
========================
Merged dict
{'a': {'b': {'t': {'w': 'test2'}}}}
Expected:
{'a': {'b': {'t': {'q': 'test', 'w': 'test2'}}}}
How can I merge dictionaries like with without losing some items?
Find the answer here
Thanks, all.

Why am I getting "None" after merging two dictionaries [duplicate]

This question already has answers here:
Why doesn't a python dict.update() return the object?
(11 answers)
Closed 6 years ago.
I have the following Python script where I merge two dictionaries:
dict1 = {'bookA': 1, 'bookB': 2, 'bookC': 3}
dict2 = {'bookC': 2, 'bookD': 4, 'bookE': 5}
print dict2.update(dict1)
Why do I get as output None rather than the merged dictionaries? How can I display the result?
Thanks.
update does not return a new dictionary.
Do this instead:
dict1 = {'bookA': 1, 'bookB': 2, 'bookC': 3}
dict2 = {'bookC': 2, 'bookD': 4, 'bookE': 5}
dict2.update(dict1)
print(dict2)
dict2.update(dict1) updates dict2, but doesn't return it. Use print dict2 instead.

Categories

Resources