merge two dictionaries with same key values - python

I have two dictionaries which consist same keys
a = {'a':[3,2,5],
'b':[9,8],
'c':[1,6]}
b = {'b':[7,4],
'c':[10,11]}
When i merge them the keys of dictionary b replaces the keys of a because of the same name. Here's the merge code I am using
z = dict(list(a.items()) + list(b.items()))
Is there somehow I can keep all the keys, I know dictionaries can't have same key name but I can work with something like this:
a = {'a':[3,2,5],
'b':[9,8],
'c':[1,6],
'b_1':[7,4],
'c_1':[10,11]}

You can use a generator expression inside the method update():
a.update((k + '_1' if k in a else k, v) for k, v in b.items())
# {'a': [3, 2, 5], 'b': [9, 8], 'c': [1, 6], 'b_1': [7, 4], 'c_1': [10, 11]}

Do something like this perhaps:
a = {'a':[3,2,5],
'b':[9,8],
'c':[1,6]}
b = {'b':[7,4],
'c':[10,11]}
z = {}
for key in a:
if key in b:
z[key + "_1"] = b[key]
z[key] = a[key]
else:
z[key] = a[key]
print(z)
Output:
{'a': [3, 2, 5], 'b_1': [7, 4], 'b': [9, 8], 'c_1': [10, 11], 'c': [1, 6]}

While I think Usman's answer is probably the "right" solution, technically you asked for this:
for key, value in b.items():
if key in a:
a[key + "_1"] = value
else:
a[key] = value

Check if key of b present in a then add in a with key_1 value of b for key other wise add in key in a the value of b for key.
a = {'a':[3,2,5],
'b':[9,8],
'c':[1,6]}
b = {'b':[7,4],
'c':[10,11]}
for k in b:
if k in a:
a[k+'_1']=b[k]
else:
a[k]=b[k]
print(a)

Related

Adding to a dictionary based on key and value from lists?

I have a dictionary defined as:
letters = {'a': 2, 'b': 1, 'c': 5}
I want to add values to this dictionary based on two lists: one which contains the keys and another which contains the values.
key_list = [a, c]
value_list = [2, 5]
This should give the output:
{a: 4, b: 1, c: 10}
Any ideas on how I can accomplish this? I am new to working with the dictionary structure so I apologise if this is extremely simple.
Thanks.
You can zip the two lists and then add to the dictionary as so;
letters = {'a': 2, 'b': 1, 'c': 5}
key_list = ['a', 'c']
value_list = [2, 5]
for k,v in zip(key_list, value_list):
letters[k] = letters.get(k, 0) + v
Using the dictionary's get() method as above allows you to add letters that aren't already in the dictionary.
for i in range(len(key_list)):
letters[key_list[i]] += value_list[i]
You can simply add or modify values from a dictionary using the key
For example:
letters = {'a': 2, 'b':1 , 'c': 5}
letters['a'] += 2
letters['c'] += 5
print(letters)
output = {'a': 4, 'b': 1, 'c': 10}

Find all index values for string t in string s?

Input:
s = "ADOBECODEBANC"
t = "ABC"
Output:
{A:[0,10] , B:[3.9], C:[5,12]}
Do we have any in built function ?
There's no builtin function, but you can use enumerate() for the task:
s = "ADOBECODEBANC"
t = "ABC"
out = {}
for i, ch in enumerate(s):
if ch in t:
out.setdefault(ch, []).append(i)
print(out)
Prints:
{'A': [0, 10], 'B': [3, 9], 'C': [5, 12]}

Python Dictionary - How to find all keys with the lowest amount of unique value?

Let's say I have a dictionary:
dict = {'a' : [1, 2], 'b' : [1], 'c' : [3, 3, 3]}
How do I find which keys have the lowest amount of unique values? In this case, it would be the dictionary with the keys 'b' and 'c' as they each only have 1 unique value.
You can create an inverted mapping using collections.defaultdict and access the keys corresponding to the least number of unique values:
from collections import defaultdict
d = {'a' : [1, 2], 'b' : [1], 'c' : [3, 3, 3]}
# dictionary mapping len of unique values to corresponding key
d2 = defaultdict(list)
for k in d:
d2[len(set(d[k]))].append(k)
print (d2)
# defaultdict(list, {2: ['a'], 1: ['b', 'c']})
print (d2[min(d2)])
# ['b', 'c']
You can do the following:
d = {'a' : [1, 2], 'b' : [1], 'c' : [3, 3, 3]} #avoid using 'dict' as name of dictionary
temp={k:len(set(v)) for k, v in d.items()} #get the count of unique values for each key
res=[i for i in temp if temp[i]==min(temp.values())] #get the keys with min value
>>> print(res)
['b', 'c']
Try like this:
d = {'a' : [1, 2], 'b' : [1], 'c' : [3, 3, 3]}
ml={i:len(set(m)) for i,m in d.items()}
res={i:d[i] for i,z in ml.items() if z==min(ml.values())}
print(res)
You can take the following three steps
# Create a dictionary d with format {key: number of unique values}
d = {key: len(set(value)) for key, value in dict.items()}
# Find the minimum value in this dictionary
min_value = min(d.values())
# Find all the keys with value equal to the minimum
min_list = [key for key, value in d.items() if value == min_value]
The result will be a list containing b and c in your example
You could use an auxiliary dict or comprehension as in other answers if you need to do further processing, otherwise IMO no need for anything fancy, a simple for loop should do the trick, using set() conversion as a quick way to count unique values
As a minor aside, it's recommended not to use dict as your dict variable name since it's a reserved keyword in python and it will shadow use of that keyword
def keys_with_fewest_uniq_values(d):
min_num_uniq, min_keys = None, []
for key, val in dict.items():
num_uniq = len(set(val))
if min_num_uniq is None or num_uniq < min_num_uniq:
min_num_uniq = num_uniq
min_keys = [key]
elif num_uniq == min_num_uniq:
min_keys.append(key)
return min_keys
>> my_dict = {'a' : [1, 2], 'b' : [1], 'c' : [3, 3, 3]}
>> print(keys_with_fewest_uniq_values(my_dict))
['b','c']

Update dictionary items with a for loop

I would like update a dictionary items in a for loop here is what I have:
>>> d = {}
>>> for i in range(0,5):
... d.update({"result": i})
>>> d
{'result': 4}
But I want d to have following items:
{'result': 0,'result': 1,'result': 2,'result': 3,'result': 4}
As mentioned, the whole idea of dictionaries is that they have unique keys.
What you can do is have 'result' as the key and a list as the value, then keep appending to the list.
>>> d = {}
>>> for i in range(0,5):
... d.setdefault('result', [])
... d['result'].append(i)
>>> d
{'result': [0, 1, 2, 3, 4]}
Keys have to be unique in a dictionnary, so what you are trying to achieve is not possible. When you assign another item with the same key, you simply override the previous entry, hence the result you see.
Maybe this would be useful to you?
>>> d = {}
>>> for i in range(3):
... d['result_' + str(i)] = i
>>> d
{'result_0': 0, 'result_1': 1, 'result_2': 2}
You can modify this to fit your needs.
PHA in dictionary the key cant be same :p in your example
{'result': 0,'result': 1,'result': 2,'result': 3,'result': 4}
you can use list of multiplw dict:
[{},{},{},{}]
You can't have different values for the same key in your dictionary. One option would be to number the result:
d = {}
for i in range(0,5):
result = 'result' + str(i)
d[result] = i
d
>>> {'result0': 0, 'result1': 1, 'result4': 4, 'result2': 2, 'result3': 3}
d = {"key1": [8, 22, 38], "key2": [7, 3, 12], "key3": [5, 6, 71]}
print(d)
for key, value in d.items():
value_new = [sum(value)]
d.update({key: value_new})
print(d)
>>> d = {"result": []}
>>> for i in range(0,5):
... d["result"].append(i)
...
>>> d
{'result': [0, 1, 2, 3, 4]}

convert n equal length lists to dictionary with unique keys from one list

I have n lists of equal length representing values of database rows. The data is pretty complicated, so i'll present simplified values in the example.
Essentially, I want to map the values of these lists (a,b,c) to a dictionary where the keys are the set of the list (id).
Example lists:
id = [1,1,1,2,2,2,3,3,3]
a = [1,2,3,4,5,6,7,8,9]
b = [10,11,12,13,14,15,16,17,18]
c = [20,21,22,23,24,25,26,27,28]
Needed dictionary output:
{id:[[a],[b],[c]],...}
{'1':[[1,2,3],[10,11,12],[20,21,22]],'2':[[4,5,6],[13,14,15],[23,24,25]],'3':[[7,8,9],[16,17,18],[26,27,28]]}
The dictionary now has a list of lists for the values in the original a,b,c subsetted by the unique values in the id list which is now the dictionary key.
I hope this is clear enough.
Try this:
id = ['1','1','1','2','2','2','3','3','3']
a = [1,2,3,4,5,6,7,8,9]
b = [10,11,12,13,14,15,16,17,18]
c = [20,21,22,23,24,25,26,27,28]
from collections import defaultdict
d = defaultdict(list)
# add as many lists as needed, here n == 3
lsts = [a, b, c]
for ki, kl in zip(id, zip(*lsts)):
d[ki] += [kl]
for k, v in d.items():
# if you don't mind using tuples, simply do this: d[k] = zip(*v)
d[k] = map(list, zip(*v))
The result is exactly as expected according to the question:
d == {'1':[[1,2,3],[10,11,12],[20,21,22]],
'2':[[4,5,6],[13,14,15],[23,24,25]],
'3':[[7,8,9],[16,17,18],[26,27,28]]}
=> True
IDs = [1,1,1,2,2,2,3,3,3]
a = [1,2,3,4,5,6,7,8,9]
b = [10,11,12,13,14,15,16,17,18]
c = [20,21,22,23,24,25,26,27,28]
import itertools
d = {}
for key, group in itertools.groupby(sorted(zip(IDs, a, b, c)), key=lambda x:x[0]):
d[key] = map(list, zip(*group)[1:]) # [1:] to get rid of the ID
print d
OUTPUT:
{1: [[1, 2, 3], [10, 11, 12], [20, 21, 22]],
2: [[4, 5, 6], [13, 14, 15], [23, 24, 25]],
3: [[7, 8, 9], [16, 17, 18], [26, 27, 28]]}

Categories