Reputation: 19
I want to loop through my_list and comparing the list items to the key in my_dict. How do I update the nested value of '0'
for each time an item in the my_list matches the my_dict key?
my_list = [1102, 4611, 4624, 4634, 1102, 1102, 4611, 1102]
my_dict = {'1102':{'count':0},'4611':{'count':0},'4624':{'count':0}}
for item in my_list:
if item in my_dict.keys():
# count:0 +=1
Upvotes: 1
Views: 41
Reputation: 3528
You can try this:
my_list = [1102, 4611, 4624, 4634, 1102, 1102, 4611, 1102]
my_dict = {'1102':{'count':0},'4611':{'count':0},'4624':{'count':0}}
for item in my_list:
if str(item) in my_dict.keys():
my_dict[str(item)]['count'] += 1
print(my_dict)
# {'1102': {'count': 4}, '4611': {'count': 2}, '4624': {'count': 1}}
While using the if
statement, don't forget to convert the type
of the item
from int
to str
Upvotes: 1