How to Create a Dictionary Merging Values Based on Keys? - python

I need to create a dictionary mapping a keys to merged values.
Let's say I got key value pairs with a duplicated key 40: {40: "lamb"}, {40: "dog"}, {50: "chicken"}
list_key = (40, 40, 50)
new_value = ("lamb", "dog", "chicken")
new_dict = {}
for i in list_key:
if i not in new_dict:
new_dict[list_key] = new_value
else:
new_dict[?] = new_value
return new_dict
This is where I get stuck.
What i need is {40: ("lamb", "dog"), 50: ("chicken")}.
How can I get this?

One way is to create a list if the key doesn't exist. Then, just append to that list whenever you encounter a relevant key.
keys = [40, 40, 50]
values = ["lamb", "dog", "chicken"]
d = {}
for k, v in zip(keys, values):
if k not in d:
d[k] = []
d[k].append(v)
...Though you can do this more prettily with collections.defaultdict:
keys = [40, 40, 50]
values = ["lamb", "dog", "chicken"]
d = defaultdict(lambda: [])
for k, v in zip(keys, values):
d[k].append(v)

Related

How can I get multiple shared items between two dictionaries in Python?

length_word = {'pen':3, 'bird':4, 'computer':8, 'mail':4}
count_word = {'pen':10, 'bird':50, 'computer':3, 'but':45, 'blackboard': 12, 'mail':12}
intersection = length_word.items() - count_word.items()
common_words = {intersection}
Err: TypeError: unhashable type: 'set'
I wish to get this dictionary:
outcome = {'pen':10, 'bird':50, 'computer':3, 'mail':12}
Thanks.
You should use .keys() instead of .items().
Here is a solution:
length_word = {'pen':3, 'bird':4, 'computer':8, 'mail':4}
count_word = {'pen':10, 'bird':50, 'computer':3, 'but':45, 'blackboard': 12, 'mail':12}
intersection = count_word.keys() & length_word.keys()
common_words = {i : count_word[i] for i in intersection}
#Output:
{'computer': 3, 'pen': 10, 'mail': 12, 'bird': 50}
intersection = count_word.keys() & length_word.keys()
outcome = dict((k, count_word[k]) for k in intersection)
try getting the intersection (common keys). one you have the common keys access those keys from the count_words.
res = {x: count_word.get(x, 0) for x in set(count_word).intersection(length_word)}
res:
{'bird': 50, 'pen': 10, 'computer': 3, 'mail': 12}
Just another dict comp:
outcome = {k: v for k, v in count_word.items() if k in length_word}
Using for loop check if the key is present in both the dictionary. If so then add that key, value pair to new dictionary.
length_word = {'pen':3, 'bird':4, 'computer':8, 'mail':4}
count_word = {'pen':10, 'bird':50, 'computer':3, 'but':45, 'blackboard': 12, 'mail':12}
my_dict = {}
for k, v in count_word.items():
if k in length_word.keys():
my_dict[k] = v
print(my_dict)

Dict Comprehension: appending to a key value if key is present, create a new key:value pair if key is not present

My code is as follows:
for user,score in data:
if user in res.keys():
res[user] += [score]
else:
res[user] = [score]
where data is a list of lists arranged as such:
data = [["a",100],["b",200],["a",50]]
and the result i want is:
res = {"a":[100,50],"b":[200]}
Would it be possible to do this with a single dictionary comprehension?
This can be simplified using dict.setdefault or collections.defaultdict
Ex:
data = [["a",100],["b",200],["a",50]]
res = {} #or collections.defaultdict(list)
for k, v in data:
res.setdefault(k, []).append(v) #if defaultdict use res[k].append(v)
print(res)
Output:
{'a': [100, 50], 'b': [200]}
you could use .update for your dictionary..
data = [["a",100],["b",200],["a",50]]
dictionary = dict()
for user,score in data:
if user in dictionary.keys():
dictionary[user] += [score]
else:
dictionary.update({user:[score]})
output:
{'a': [100, 50], 'b': [200]}

Convert python dict "key value" into dict having "k(value) ey"

I have a dict
d = {'A1BB11': 10,
'B1CC55': 20,
'A1A11': 30,
'A1A21': 40,
'B1HH21': 50,
'C1KK88': 60
}
I want to get a new dict from prev dict d
new_d = {'A1(80)':['BB11', 'A11', 'A21'],
'B1(70)':['CC55', 'HH21'],
'C1(60)':['KK88']
}
Could you provide a simple pythonic way to it? I am new to python world.
I think the simplest way would be to create two dictionaries to track the two values you're concerned with: the sums and the lists of suffixes.
from collections import defaultdict
d1, d2 = defaultdict(int), defaultdict(list)
d = {'A1BB11': 10,
'B1CC55': 20,
'A1A11': 30,
'A1A21': 40,
'B1HH21': 50,
'C1KK88': 60
}
for k, v in d.items():
prefix = k[:2]
d1[prefix] += v
d2[prefix].append(k[2:])
final = {'{}({})'.format(k, d1[k]): v for k, v in d2.items()}
print(final)
# {'A1(80)': ['BB11', 'A11', 'A21'],
# 'B1(70)': ['CC55', 'HH21'],
# 'C1(60)': ['KK88']}

Renaming the key in a list of dicts

I have a list of dicts:
[{"id" : "2016_a",
"data_1" : 106,
"data_2" : 200},
{"id" : "2015_a",
"data_1" : 110,
"data_2" : 105}
]
I wish to take the id record and use it to create a single, unique list of dicts, such that:
[{"data_1_2016_a" : 106,
"data_1_2015_a" : 110,
"data_2_2016_a" : 200,
"data_2_2015_a" : : 105}]
How do I append the string id to the key value of each other record?
It's simple to loop through and assign.
result = {}
for elem in data:
for k, v in elem.items():
if k != 'id':
result['{}_{}'.format(elem['id'], k)] = v
You can simply use dictionary comprehension:
result = {dic['id']+'_'+k:v for dic in dictionaries
for k,v in dic.items() if k != 'id'}
You can (probably) improve efficiency a bit by using a generator inside:
result = {dicid+k:v for dic,dicid in ((_dic,_dic['id']+'_') for _dic in dictionaries)
for k,v in dic.items() if k != 'id'}
Here we save on lookups (dic['id']) and we also have to append the underscore only once. This results in:
>>> {dicid+k:v for dic,dicid in ((_dic,_dic['id']+'_') for _dic in dictionaries)
... for k,v in dic.items() if k != 'id'}
{'2016_a_data_1': 106, '2015_a_data_2': 105, '2016_a_data_2': 200, '2015_a_data_1': 110}

Separating dictionary into smaller dictionaries

I have a dictionary and want to divide it into smaller dictionaries, for example for:
dic = {1:(2,6), 3:(4,5)}
I want to loop it and have a "current" dictionary current = {1:2, 3:4} for first iteration, and current {1:6, 3:5} for the second iteration. Here's what I've tried (and doesn't work):
dic = {1:(2,6), 3:(4,5)}
for i in range (0,1):
for key in dic:
current = {}
current[key] = dic[key][i]
print (current)
this outputs {3:4} and {3:5}, it skips the key "1" for some reason. How do i fix this?
Also, how do I find the number of the values of the keys assuming every key has equal number of values? e.g. for {2:[3,4,5,7], 3:[1,0,3,1]} that would be 4.
You are overwriting current on each iteration, define it before iterating, and range(0, 1) loops through [0] only:
dic = {1:(2,6), 3:(4,5)}
for i in range(2):
current = {}
for key in dic:
current[key] = dic[key][i]
print(current)
Alternatively, you could create the new dictionaries, iterate through the keys of the original dict and create the dictionaries accordingly:
dic = {1:(2,6), 3:(4,5)}
d1, d2 = {}, {}
for key, v in dic.items():
d1[key], d2[key] = v
print(d1, d2)
Which prints out:
{1: 2, 3: 4} {1: 6, 3: 5}
d1[key], d2[key] = v simply unpacks the value for v in d1[key] and d2[key] accordingly.

Categories