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}
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']
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]}
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]]}