I have two separate dictionaries with keys and values that I would like to multiply together. The values should be multiplied just by the keys that they have.
i.e.
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 15, 'b': 10, 'd': 17}
dict3 = dict.items() * dict.items()
print dict3
#### #dict3 should equal
{'a': 15, 'b': 20}
If anyone could help, that would be great.
Thanks!
You can use a dict comprehension:
>>> {k : v * dict2[k] for k, v in dict1.items() if k in dict2}
{'a': 15, 'b': 20}
Or, in pre-2.7 Python, the dict constructor in combination with a generator expression:
>>> dict((k, v * dict2[k]) for k, v in dict1.items() if k in dict2)
{'a': 15, 'b': 20}
From my telephone, so bit hard to type code. This should do the trick:
for key, value in dict1.iteritems():
if key in dict2:
dict3[key] = int(dict1[key]) * int(dict2[key])
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 15, 'b': 10, 'd': 17}
def dict_mul(d1, d2):
d3 = dict()
for k in d1:
if k in d2:
d3[k] = d1[k] * d2[k]
return d3
print dict_mul(dict1, dict2)
Related
Do I have any opportunity to rewrite the code below with dict enhancement? (if I name it right, mean {k: v for k, v in ...})
list_of_dicts = [{'a': 1}, {'b': 2}, {'b': 20, 'c': 3}, {'a': 10, 'b': 2}]
for k, v in [p for d in list_of_dicts for p in d.items()]:
d[k] = d.setdefault(k, set()) | {v}
sure why not :). but it is nested at bit 😉
import itertools
list_of_dicts = [{'a': 1}, {'b': 2}, {'b': 20, 'c': 3}, {'a': 10, 'b': 2}]
o = {k: {d[k] for d in list_of_dicts if k in d} for k in itertools.chain.from_iterable(list_of_dicts)}
print(o)
dict1 = {'a': 10, 'b': 8, 'c':5}
dict2 = {'d': 6, 'c': 4, 'a':20}
Given two dictionaries, I'd like an output of.
output = {'a':30, 'b':8, 'c':9, 'd':6}
This is what I've so far, not quite sure what I'd do next.
I'm looking for a solution that is efficient in time/space complexity.
def merge_dict(dict1, dict2):
merged_dictionaries = {**dict1, **dict2}
return merged_dictionaries
dict1 = {'a': 10, 'b': 8, 'c':5}
dict2 = {'d': 6, 'c': 4, 'a':20}
merge_dictionaries = merge_dict (dict1, dict2)
sorted_dictionary = sorted(merge_dictionaries)
If the values are numeric, you can use counters:
from collections import Counter
def merge_dicts(*dicts):
return dict(sum(map(Counter, dicts), Counter()))
dict1 = merge_dicts(dict1, dict2)
dict1
# {'a': 30, 'b': 8, 'c': 9, 'd': 6}
This might be a bit excessive for only two dictionaries, so another option is:
for k, v in dict2.items():
dict1[k] = dict1.setdefault(k, 0) + v
dict1
# {'a': 30, 'b': 8, 'c': 9, 'd': 6}
Which updates dict1 in-place.
Finally, if you really need the result sorted (python3.7+), use
result = {k : dict1[k] for k in sorted(dict1)}
You can use a dict comprehension that iterates over a sorted union of the keys of the two dicts, and outputs values that are sums of the respective values of two dicts by the given keys, defaulting to 0:
{k: dict1.get(k, 0) + dict2.get(k, 0) for k in sorted(dict1.keys() | dict2.keys())}
This returns:
{'a': 30, 'b': 8, 'c': 9, 'd': 6}
result = dict(Counter(dict1) + Counter(dict2))
result = {k: result[k] for k in sorted(result)}
First merge the dicts together by turning them into Counters and convert the result it back into a dict, then sort the dict by keys.
You can Try Collections for add two dictionary..
from collections import Counter
def merged_dic():
dict1 = {'a': 10, 'b': 8, 'c':5}
dict2 = {'d': 6, 'c': 4, 'a':20}
a = Counter(dict1)
b = Counter(dict2)
c = a+b
print(dict(c))
merged_dic()
Output:- {'a': 30, 'b': 8, 'c': 9, 'd': 6}
So I have this block of code
dictionary = {
'key1': {'a': 1, 'b': 2, 'c': 10},
'key2': {'d': 1, 'e': 1, 'c': 11},
'key3': {'d': 2, 'b': 1, 'g': 12}}
and
list1 = (a,b,c)
What I want to do is run a loop that finds the maximums of all the items in the list and returns the key. So for example, the maximum of 'c' would return 'key2', the maximum of 'b' would return 'key1', etc.
So far I have
for value in list1:
m = max(dictionary, key=lambda v: dictionary[v][value])
print(m + "\n")
But this only works if the same subkey exists in all keys in the dictionary. Any ideas on what to do?
Use float('-inf') when the key is missing:
m = max(dictionary, key=lambda v: dictionary[v].get(value, float('-inf')))
Negative infinity is guaranteed to be smaller than any existing value in the dictionaries, ensuring that nested dictionaries with the specific key missing are ignored.
Demo:
>>> dictionary = {
... 'key1': {'a': 1, 'b': 2, 'c': 10},
... 'key2': {'d': 1, 'e': 1, 'c': 11},
... 'key3': {'d': 2, 'b': 1, 'g': 12}}
>>> list1 = ('a', 'b', 'c')
>>> for value in list1:
... print(value, max(dictionary, key=lambda v: dictionary[v].get(value, float('-inf'))))
...
a key1
b key1
c key2
However, it'll be more efficient if you looped over all your dictionary values just once instead:
maximi = dict.fromkeys(list1, (None, float('-inf')))
for key, nested in dictionary.items():
for k in nested.keys() & maximi: # intersection of keys
if maximi[k][0] is None or dictionary[maximi[k][0]][k] < nested[k]:
maximi[k] = (key, nested[k])
for value in list1:
print(value, maximi[value][0])
That's presuming you are using Python 3; in Python 2, replace .items() with .iteritems() and .keys() with .viewkeys().
Demo:
>>> maximi = dict.fromkeys(list1, (None, float('-inf')))
>>> for key, nested in dictionary.items():
... for k in nested.keys() & maximi: # intersection of keys
... if maximi[k][0] is None or dictionary[maximi[k][0]][k] < nested[k]:
... maximi[k] = (key, nested[k])
...
>>> maximi
{'a': ('key1', 1), 'b': ('key1', 2), 'c': ('key2', 11)}
>>> for value in list1:
... print(value, maximi[value][0])
...
a key1
b key1
c key2
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
How can one compare two different dictionaries using dictionary comprehension, in similar fashion as list comprehension. For example, given:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 3, 'b': 10, 'c': 4}
#create another dict which contains key-(value1 x value2)
dict3 = {'a': 3, 'b': 20, 'c': 12}
>>> dict1 = {'a': 1, 'b': 2, 'c': 3}
>>> dict2 = {'a': 3, 'b': 10, 'c': 4}
>>> { k: v * dict2[k] for k, v in dict1.items() if k in dict2 }
{'a': 3, 'b': 20, 'c': 12}
This includes a check that only those items will be multiplicated which keys exist in both dictionaries. And alternatively, you can swap dict1 and dict2 for the same effect.
Create an intersection of the keys, then access the value in both dictionaries:
{k: dict1[k] * dict2[k] for k in dict1.viewkeys() & dict2}
This uses dictionary views which act as sets (and & creates a set intersection).
In Python 3 you get dicitonary views via the default methods:
{k: dict1[k] * dict2[k] for k in dict1.keys() & dict2}
By using the key set intersection, you ensure you only get keys that appear in both dictionaries.
Assuming all keys are shared:
>>> dict1 = {'a': 1, 'b': 2, 'c': 3}
>>> dict2 = {'a': 3, 'b': 10, 'c': 4}
>>> {k: dict1[k] * dict2[k] for k in dict1}
{'a': 3, 'c': 12, 'b': 20}
If the keys aren't shared:
>>> dict1 = {'a': 1, 'b': 2, 'c': 3}
>>> dict2 = {'a': 3, 'b': 10, 'd': 4} # no 'c' key
>>> {k: dict1[k] * dict2[k] for k in dict1 if k in dict2}
{'a': 3, 'b': 20}
If I have:
dicts = [{'a': 4,'b': 7,'c': 9},
{'a': 2,'b': 1,'c': 10},
{'a': 11,'b': 3,'c': 2}]
How can I get the maximum keys only, like this:
{'a': 11,'c': 10,'b': 7}
Use collection.Counter() objects instead, or convert your dictionaries:
from collections import Counter
result = Counter()
for d in dicts:
result |= Counter(d)
or even:
from collections import Counter
from operator import or_
result = reduce(or_, map(Counter, dicts), Counter())
Counter objects support finding the maximum per key natively through the | operation; & gives you the minimum.
Demo:
>>> result = Counter()
>>> for d in dicts:
... result |= Counter(d)
...
>>> result
Counter({'a': 11, 'c': 10, 'b': 7})
or using the reduce() version:
>>> reduce(or_, map(Counter, dicts), Counter())
Counter({'a': 11, 'c': 10, 'b': 7})
>>> dicts = [{'a': 4,'b': 7,'c': 9},
... {'a': 2,'b': 1,'c': 10},
... {'a': 11,'b': 3,'c': 2}]
>>> {letter: max(d[letter] for d in dicts) for letter in dicts[0]}
{'a': 11, 'c': 10, 'b': 7}
dicts = [{'a': 4,'b': 7,'c': 9},
{'a': 2,'b': 1,'c': 10},
{'a': 11,'b': 3,'c': 2}]
def get_max(dicts):
res = {}
for d in dicts:
for k in d:
res[k] = max(res.get(k, float('-inf')), d[k])
return res
>>> get_max(dicts)
{'a': 11, 'c': 10, 'b': 7}
Something like this should work:
dicts = [{'a': 4,'b': 7,'c': 9},
{'a': 2,'b': 1,'c': 10},
{'a': 11,'b': 3,'c': 2}]
max_keys= {}
for d in dicts:
for k, v in d.items():
max_keys.setdefault(k, []).append(v)
for k in max_keys:
max_keys[k] = max(max_keys[k])