This question already has answers here:
Intersection and Difference of two dictionaries
(2 answers)
Closed 6 years ago.
I am trying to handle values from two different dictionaries in Python.
What I need to do is operate with values which have the same key in both dictionaries.
For instance, if dictionaries are:
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
I need to add values from keys 1, 2 and 3 from each dictionary.
I am trying to make an iterable of values, but, when I try to extend an empty iterable with values with a line such as:
sameKeys.extend(d1[i]))
I get an Error Key. I have tried many differents syntax but none has worked.
You can try like this,
for i,j in zip(d1.items(),d2.items()):
if i[0] == j[0]:
print i[1]+j[1]
Result
70
70
90
Iterate over any of the dict. Check whether key exists in second list. If it exists, make an entry into new dict. Below is the sample example:
>>> d1 = {1:30, 2:20, 3:30, 5:80}
>>> d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
>>> d3 = {}
>>> for key, value in d1.items():
... if key in d2:
... d3[key] = value + d2[key]
...
>>> d3
{1: 70, 2: 70, 3: 90}
>>>
Here is one option:
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
dlist = [d1, d2]
# As a dict comprehension
result = {k: sum(d[k] for d in dlist)
for k in set.intersection(*[set(d) for d in dlist])}
print result
# Same as above, but as for loops
result = {}
repeated_keys = set(d1)
for d in dlist:
repeated_keys &= set(d)
for k in repeated_keys:
result[k] = 0
for d in dlist:
result[k] += d[k]
print result
Related
Write a python program to filter a dictionary based on values that are the multiples of 6
NOTE:
Take keys as strings and values as integers.
Constraints:
1<=number of key value pairs<=10
Sample test case: keys : a,b,c,d,e,f values:1,2,3,4,5,6 {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6} {'f':6}
You can use a dict comprehension.
d = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
res = {k:v for k,v in d.items() if v % 6 == 0}
print(res)
old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}
#or this it will work totally perfect
#old_dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13}
print (f"Original dictionary is : {old_dict}")
print()
new_dict = {key:value for (key, value) in old_dict.items() if value % 6 == 0}
print(f"New dictionary with multiple of 6 is : {new_dict}")
Suppose I have a dictionary:
d = {'a_c':1,'b_c':2,'a_d':3,'b_d':4}
how do I split into two based on the last word/letter of the key ('c','d') like this?
d1 = {'a_c':1,'b_c':2}
d2 = {'a_d':3,'b_d':4}
This is one way:
from collections import defaultdict
d = {'a_c':1,'b_c':2,'a_d':3,'b_d':4}
key = lambda s: s.split('_')[1]
res = defaultdict(dict)
for k, v in d.items():
res[key(k)][k] = v
print(list(res.values()))
Output:
[{'a_c': 1, 'b_c': 2}, {'a_d': 3, 'b_d': 4}]
The result is a list of dictionaries divided on the last letter of the key.
You could try something like this:
func = lambda ending_str: {x: d[x] for x in d.keys() if x.endswith(ending_str)}
d1 = func('_c')
d2 = func('_d')
Also, like Marc mentioned in the comments, you shouldn't have two same name keys in the dictionary. It will only keep the last key/value pair in that case.
I'd like two join two dictionaries based on the value of d1 and a substring of the key of d2. The resulting dictionary has the key of d1 with the corresponding value of d2.
d1 = {'web02': '23', 'web01': '50'}
d2 = {'server/dc-50': 's01.local', 'server/dc-23': 's02.local'}
Would result in = {web01:s01.local, web02:s02.local}
I guess this is what you need :
result = {k1:v2 for k1,v1 in d1.items() for k2,v2 in d2.items() if v1 in k2}
Output :
{'web02': 's02.local', 'web01': 's01.local'}
This is done without a nested loop by getting the value using string formatting:
data = {k: d2['server/dc-' + v] for k, v in d1.items()}
Prints:
{'web02': 's02.local', 'web01': 's01.local'}
This question already has answers here:
Sum corresponding elements of multiple python dictionaries
(4 answers)
Closed 2 years ago.
Given three dicts d1, d2 and d3:
d1
{'a':1,'b':2,'c':3, 'd':0)
d2
{'b':76}
d3
{'a': 45, 'c':0}
There are some key names that are common to more than one dict (and in reality, they will represent the same real-life object). Others such as 'd' in d1 only exist in d2. I want to group all dicts together, first summing the values of the common keys first, ending up with:
{'a':46, 'b':78, 'c':3, 'd': 0}
If every dict were the same size and contained the same keys, I could do something like:
summedAndCombined = {}
for k,v in d1.items():
summedAndCombined[k] = d1[k]+d2[k]+d3[k]
But this will break down as soon as it reaches a key that is in d1 but not in the others. How do we achieve this?
UPDATE
Not a duplicate. collections.Counter almost works, but the key d is missing from the resulting Counter if the value of key d is zero, which it is above.
In [128]: d1 = {'a':1,'b':2,'c':3, 'd':0}
In [129]: d2 = {'b':76}
In [130]: d3 = {'a': 45, 'c':0}
In [131]: from collections import Counter
In [132]: Counter(d1) + Counter(d2) + Counter(d3)
Out[132]: Counter({'b': 78, 'a': 46, 'c': 3})
You could use update instead of + with Counter if you want the 0 keys to persist:
>>> c = Counter()
>>> for d in d1, d2, d3:
... c.update(d)
...
>>> c
Counter({'b': 78, 'a': 46, 'c': 3, 'd': 0})
(This is probably a dup, but I can't find it right now.)
collections.defaultdict to the rescue
import collections
d = collections.defaultdict(int)
for thing in [d1, d2, d3]:
for k, v in thing.items():
d[k] += v
UNTESTED:
def merge_dicts(*dicts):
res = {}
for key in set(sum(map(list, dicts), [])):
res[key] = 0
for dct in dicts:
res[key] += dct.get(key, 0)
return res
Example usage:
merge_dicts(d1, d2, d3)
This question already has answers here:
Order of keys in dictionaries in old versions of Python
(6 answers)
Closed 8 years ago.
I've run into a problem with looping through a dictionary. The following code:
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
for k,v in d.iteritems():
print k,v
Results in:
a 1
c 3
b 2
But the desired result is:
a 1
b 2
c 3
Does anyone know how to fix the loop somehow to preserve the order that the elements were assigned in? Thank you!
In Python, normal dictionaries were designed to be unordered. Meaning, they should not be used here.
Instead, you should use a collections.OrderedDict:
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d['a'] = 1
>>> d['b'] = 2
>>> d['c'] = 3
>>> for k,v in d.iteritems():
... print k,v
...
a 1
b 2
c 3
>>>
Unlike a normal dictionary, an OrderedDict is guaranteed to preserve the order in which the elements were assigned.
A dictionary does not preserve order, so you need to sort the keys:
for k,v in sorted(d.iteritems,key=lambda x: x[0]):
print k,v
Alternatively, use a collections.OrderedDict object which internally maintains a list of keys in insertion order:
import collections
d = collections.OrderedDict()
...
for k,v in d.iteritems():
print k,v