I have a dictionary as follows:
d= {'a':['the','the','an','an'],'b':['hello','hello','or']}
I want to convert this dictionary into a nested dictionary with values of a key and their count as follows:
d = {'a':{'the':2,'an':2},'b':{'hello':2,'or':1}}
I can count the values for a dictionary as follows but unable to turn the values to another dictionary with their counts.
length_dict = {key: len(value) for key, value in d.items()}
You can use collections.Counter instead:
from collections import Counter
{k: dict(Counter(v)) for k, v in d.items()}
This returns:
{'a': {'the': 2, 'an': 2}, 'b': {'hello': 2, 'or': 1}}
d= {'a':['the','the','an','an'],'b':['hello','hello','or']}
I think thig ough to do it :
from collections import Counter
new_dict = {}
for k in d.keys():
aux_counter = Counter(d[k])
new_dict [k] = {}
for c, v in zip(aux_counter.keys(), aux_counter.values()):
new_dict[k][c] = v
A dictionary comprehension using Counter
from collections import Counter
{k:{p:q for p,q in Counter(v).items()} for k,v in d.items()}
Without using Counter
def count_values(v):
d={}
for i in v:
d[i]=d.get(i,0)+1
return d
{k:{p:q for p,q in count_values(v).items()} for k,v in d.items()}
Giving you more options using Pandas(not required) here but still
from pandas import Series
df = pd.DataFrame(dict([ (k,Series(v)) for k,v in d.items() ]))
{c:df[c].value_counts().to_dict() for c in df.columns}
Related
I have a python dictionary and I'd like to concatenate the values of value[0] and a list in value [1]
so
dict={ 'Key1':['MASTER',['_A','_B','_C']]}
and expected output is of calling Key1 is
[['MASTER_A','MASTER_B','MASTER_C']]
Use a nested comprehension:
d = {'Key1':['MASTER',['_A','_B','_C']]}
result_dict = {k: [v[0] + l for l in v[1]] for k,v in d.items()}
For example:
>>> result_dict = {k: [v[0] + l for l in v[1]] for k,v in d.items()}
>>> result_dict
{'Key1': ['MASTER_A', 'MASTER_B', 'MASTER_C']}
Try this :
d = {'Key1':['MASTER',['_A','_B','_C']]}
out = [d['Key1'][0]+i for i in d['Key1'][1]]
Output :
['MASTER_A', 'MASTER_B', 'MASTER_C']
To assign it to the key, do :
d['Key1'] = out
Suppose I have a dictionary as follows
dic = {0: [1,2,3,4,5], 1:[7,4,6]}
While printing the dictionary as key and count, first updating the dictionary
for k, v in dic.items():
dic[k] = len(v)
print(dic)
>>> {0:5, 1:3}
Is there a better way to do the above without for loop?
What do you mean saying without iteration? If you don't want to use a for loop, you can use a map function:
d = dict(map(lambda kv: (kv[0], len(kv[1])), d.items()))
If by no iteration you simply mean to do it without a for loop, you can map the dict values to the len function, zip them with the dict keys and pass the zipped key-value pairs to the dict constructor:
>>> d = {0: [1,2,3,4,5], 1:[7,4,6]}
>>> dict(zip(d, map(len, d.values())))
{0: 5, 1: 3}
>>>
First of all do not name a list 'list' or a dictionary 'dict', as this is a reserved word in python for the class that holds that data type.
You can do it neatly using dictionary comprehension as follows:
d = {0: [1,2,3,4,5], 1:[7,4,6]}
d = {i:len(j) for i,j in d.items()}
print(d)
Or use:
print({k:len(dic[k]) for k in dic})
Output:
{0: 5, 1: 3}
I want to merge all the dictionaries in a dictionary, while ignoring the main dictionary keys, and summing the value of the other dictionaries by value.
Input:
{'first':{'a': 5}, 'second':{'a': 10}, 'third':{'b': 5, 'c': 1}}
Output:
{'a': 15, 'b': 5, 'c': 1}
I did:
def merge_dicts(large_dictionary):
result = {}
for name, dictionary in large_dictionary.items():
for key, value in dictionary.items():
if key not in result:
result[key] = value
else:
result[key] += value
return result
Which works, but I don't think it's such a good way (or less "pythonic").
By the way, I don't like the title I wrote. If anybody thinks of a better wording please edit.
You can sum counters, which are a dict subclass:
>>> from collections import Counter
>>> sum(map(Counter, d.values()), Counter())
Counter({'a': 15, 'b': 5, 'c': 1})
This will work
from collections import defaultdict
values = defaultdict(int)
def combine(d, values):
for k, v in d.items():
values[k] += v
for v in a.values():
combine(v, values)
print(dict(values))
Almost similar, but it's just short and I like it a little better.
def merge_dicts(large_dictionary):
result = {}
for d in large_dictionary.values():
for key, value in d.items():
result[key] = result.get(key, 0) + value
return result
I have a list:
list = [(a,1),(b,2),(a,3)]
I want to convert it to a dict where when there is a duplicate (eg. (a,1) and (a,3)), it will be get the average so dict will just have 1 key:value pair which would be in this case a:2.
from collections import defaultdict
l = [('a',1),('b',2),('a',3)]
d = defaultdict(list)
for pair in l:
d[pair[0]].append(pair[1]) #add each number in to the list with under the correct key
for (k,v) in d.items():
d[k] = sum(d[k])/len(d[k]) #re-assign the value associated with key k as the sum of the elements in the list divided by its length
So
print(d)
>>> defaultdict(<type 'list'>, {'a': 2, 'b': 2})
Or even nicer and producing a plain dictionary in the end:
from collections import defaultdict
l = [('a',1),('b',2),('a',3)]
temp_d = defaultdict(list)
for pair in l:
temp_d[pair[0]].append(pair[1])
#CHANGES HERE
final = dict((k,sum(v)/len(v)) for k,v in temp_d.items())
print(final)
>>>
{'a': 2, 'b': 2}
Note that if you are using 2.x (as you are, you will need to adjust the following to force float division):
(k,sum(v)/float(len(v)))
OR
sum(d[k])/float(len(d[k]))
I have,
dict1={a:1, b:2, c:3}
dict2={a:3, c:7}
I want to find out what keys I have in dict1 that I don't have in dict2. So I do
diff_as_set = set(dict1.keys()) - set (dict2.keys())
This gives me: b
However, I want a dictionary which contains all the key value mappings from dict1 for all keys that are not in dict 2 so I then do:
diff_as_dict = {k:v for k,v in dict1 if k in diff_as_set}
I get:
diff_as_dict = {k:v for k, v in dict1 if k in diff_as_set}
ValueError: too many values to unpack (expected 2)
Any ideas?
Looping over a dict only provides keys, you need to use:
diff_as_dict = {k:v for k, v in dict1.iteritems() if k in diff_as_set}
^^^^^^^^^^^
Or use .items() for Python 3.x
Instead of going through the entire dict to pick out the ones that match your set, just iterate the set.
diff_as_dict = {k:dict1[k] for k in diff_as_set}
Example:
>>> dict1={'a':1, 'b':2, 'c':3}
>>> dict2={'a':3, 'c':7}
>>> diff_as_set = set(dict1.keys()) - set (dict2.keys())
>>> diff_as_set
set(['b'])
>>> diff_as_dict = {k:dict1[k] for k in diff_as_set}
>>> diff_as_dict
{'b': 2}
You're missing the .iteritems() part:
dict1 = {'a':1, 'b':2, 'c':3}
dict2 = {'a':3, 'c':7}
newdict = {k : v for k,v in dict1.iteritems() if not(k in dict2)}
After this, newdict is equal to {'b': 2}. This does everything in one go.