This question already has answers here:
Using a dictionary to count the items in a list
(8 answers)
Closed 2 years ago.
words = ['rocky','mahesh','surendra','mahesh','rocky','mahesh','deepak','mahesh','mahesh','mahesh','surendra']
words_count = {}
for word in words:
words_count[word] = words_count.get(word, 0) + 1
print(words_count)
# Expected Output
# {'rocky': 2, 'mahesh': 6, 'surendra': 2, 'deepak': 1}
In this example, I just want to modify value of dict key while dict comprehension
Note: not looking other way to find occurrence/count of each key in dict.
You can use collections.Counter:
from collections import Counter
words_count = Counter(words)
You could count that without using any import and using as few .counts as possible following way:
words = ['rocky','mahesh','surendra','mahesh','rocky','mahesh','deepak','mahesh','mahesh','mahesh','surendra']
words_count = {i:words.count(i) for i in set(words)}
print(words_count) # {'surendra': 2, 'mahesh': 6, 'rocky': 2, 'deepak': 1}
Converting list to set will result in unique values.
A short, simple, one-liner code:
{i:words.count(i) for i in words}
Here, we create a dictionary based on the count of the word.
Gives:
{'rocky': 2, 'mahesh': 6, 'surendra': 2, 'deepak': 1}
Related
This question already has an answer here:
How to merge two lists into a dictionary and sum values for duplicate keys [duplicate]
(1 answer)
Closed 1 year ago.
This is my first time asking a question on stack overflow myself but have been using the resources here for quite a while - thanks!
list_1 = ['a','b','c','c']
list_2 = [2,2,2,2]
I want to combine both the lists and get add values of the same keys
my_dict = dict(zip(stream_ids, times))
but whenever I combine the lists to dictionaries - value for the key gets replaced by the last one
Output: {'a': 2, 'b': 2, 'c': 2}
I want both 'c' to be added to get a 4
What I want to get is
{'a': 2, 'b': 2, 'c': 4}
Any help would be really appreciated!
The most readable way would be to use a simple for loop:
stream_ids = ['a','b','c','c']
times = [2,2,2,2]
my_dict = {}
for idx, count in zip(stream_ids, times):
if idx in dict:
my_dict[idx] += count
else:
my_dict[idx] = count
You can probably do it in one line too using a lamda function and dictionary comprehension but that won't be very readable.
A dict will simply overwrite existing values. You have to build your dict by your own.
stream_ids = ['a','b','c','c']
times = [2,2,2,2]
my_dict = {}
for s, t in zip(stream_ids, times):
my_dict[s] = my_dict.get(s, 0) + t
print(my_dict) # {'a': 2, 'b': 2, 'c': 4}
A variant of other answers here, with collections.defaultdict:
from collections import defaultdict
stream_ids = ['a','b','c','c']
times = [2,2,2,2]
dict = defaultdict(int)
for idx, count in zip(stream_ids, times):
dict[idx] += count
since the default for a new integer is 0.
This question already has answers here:
Assigning keys to a dictionary from a string
(3 answers)
Closed 4 years ago.
I am trying to convert this string into a dictionary such that it produces a key-value pair where the Key is the alphabet and the Value is its corresponding position in the word: example
word = 'jazz'
word_dict = {'j':[0],'a':[1],'z':[2,3]}
This is what I am trying to do:
word = 'jazz'
word_dict = {}
for key, value in enumerate(word):
dict_word = {value:key}
print(dict_word)
The code above yeilds:
{'j': 0}
{'a': 1}
{'z': 2}
{'z': 3}
I am kind of stuck here and don't know how to proceed further so that I can update these outputs generated from the loop into a dictionary as mentioned above. I am kind of new to this so any help will be appreciated.
Thank you.
You can use a defaultdict:
from collections import defaultdict
word = 'jazz'
word_dict = defaultdict(list)
for idx, chr in enumerate(word):
word_dict[chr].append(idx)
print(word_dict)
Output:
defaultdict(list, {'j': [0], 'a': [1], 'z': [2, 3]})
The resulting defaultdict acts exactly like a real dict, but if you need it as a dict for some reason, you can call dict(word_dict). However, everywhere where a dict will work, a defaultdict will work as it's a subclass.
Is this what you are looking for?
word = 'jazz'
word_dict = {}
for key_as_value, value_as_key in enumerate(word):
if value_as_key in word_dict:
word_dict[value_as_key].append(key_as_value)
else:
word_dict[value_as_key] = [key_as_value]
print(word_dict)
# below is the output
{'j': [0], 'a': [1], 'z': [2, 3]}
Is this working what you are looking for ?
Please check this code.
word = 'jazz'
word_dict = {}
for key, value in enumerate(word):
dict_word = {value:key}
word_dict.update(dict_word)
print(dict_word)
print (word_dict)
This question already has answers here:
How can I make a dictionary (dict) from separate lists of keys and values?
(21 answers)
Closed 4 years ago.
I have an array:
classes = ["banana","mango","apple"]
I am trying to print this array in a specific format where in each element has to be numbered in a particular sequence. The desired output is as follows:
classes = [{"banana" : 1, "mango" : 2, "apple" : 3}]
I tried using a for loop as follows:
classes = ["banana","mango","apple"]
counter = 0
dat = []
for x in classes:
counter=counter+1
d = x,":", counter
dat.append(d)
print(dat)
While this prints
[('banana', ':', 1), ('mango', ':', 2), ('apple', ':', 3)]
this is far from what I require. Can someone help?
You can enumerate the input list and reverse via a dictionary comprehension.
classes = ["banana","mango","apple"]
res = {v: k for k, v in enumerate(classes, 1)}
# {'apple': 3, 'banana': 1, 'mango': 2}
There seems to be no need to put this dictionary in a list, as in your desired output.
This question already has answers here:
Initialize List to a variable in a Dictionary inside a loop
(2 answers)
Closed 5 years ago.
I have a dictionary that needs to create a key when the key first shows up and adds a value for it, later on, keeps updating the key with values by appending these values to the previous value(s), I am wondering how to do that.
outter_dict = defaultdict(dict)
num_index = 100
outter_dict['A'].update({num_index: 1})
outter_dict['A'].update({num_index: 2})
2 will replace 1 as the value for key 100 of the inner dict of outter_dict, but ideally, it should look like,
'A': {100:[1,2]}
UPDATE
outter_dict = defaultdict(list)
outter_dict['A'][1].append(2)
but I got
IndexError: list index out of range
if I do
dict['A'][1] = list()
before assign any values to 1, I got
IndexError: list assignment index out of range
You can use a collections.defaultdict:
from collections import defaultdict
d = defaultdict(list)
num_index = 100
d[num_index].append(1)
d[num_index].append(2)
print(dict(d))
Output:
{100: [1, 2]}
Regarding your most recent edit, you want to use defautldict(dict) and setdefault:
outter_dict = defaultdict(dict)
outter_dict["A"].setdefault(1, []).append(2)
print(dict(outter_dict))
Output:
{'A': {1: [2]}}
This question already has answers here:
Extract a subset of key-value pairs from dictionary?
(14 answers)
Filter dict to contain only certain keys?
(22 answers)
Closed 5 years ago.
Dictionary:
d = {'a':[2,3,4,5],
'b':[1,2,3,4],
'c':[5,6,7,8],
'd':[4,2,7,1]}
I want to have d_new which containes only b and c items.
d_new = {'b':[1,2,3,4],
'c':[5,6,7,8]}
I want a scalable solution
EDIT:
I also need a method to create a new dictionary by numbers of items:
d_new_from_0_to_2 = {'a':[2,3,4,5],
'b':[1,2,3,4]}
If you want a general way to pick particular keys (and their values) from a dict, you can do something like this:
d = {'a':[2,3,4,5],
'b':[1,2,3,4],
'c':[5,6,7,8],
'd':[4,2,7,1]}
selected_keys = ['a','b']
new_d = { k: d[k] for k in selected_keys }
Gives:
{'a': [2, 3, 4, 5], 'b': [1, 2, 3, 4]}
I think that in Python 2.6 and earlier you would not be able to use a dict comprehension, so you would have to use:
new_d = dict((k,d[k]) for k in selected_keys)
Is this what you want?
new_d = dict(b=d.get('b'), c=d.get('c'))