Reputation: 105
Given a list:
lst = ['apple', 'orange', 'pears', 'pears', 'banana']
and a dictionary
dict = {'orange': 4, 'apple':2, 'pears': 1}
if a string from the list already exist in dict update the value else add a new key and its counting.
result:
dict = {'orange' = 5, 'apple':3, 'pears':3, 'banana':1}
I tried:
count = 0
for string on lst:
if string in dict.keys():
for num in dict:
count = count + num
num = count
I don't know how to continue
Upvotes: 0
Views: 2651
Reputation: 1
Before extending, there is a typo in line 2, which should be for string in list.
This is my suggested solution. As you iterate through the list, check each entry to see if it is a key in the dictionary (as you have already done). If it is, the dict[string] will be the number value paired with that key and you can add one to it. If not, then you can add the string as a new key with a value of 1.
# original data
lst = ['apple', 'orange', 'pears', 'pears', 'banana']
dict = {'orange': 4, 'apple':2, 'pears': 1}
# iterate through lst and add 1 to each corresponding key value
for string in lst:
if string in dict.keys():
# increment count for a found key
# which can be accessed in dict[string] - no need for num
count = int(dict[string])
dict[string] = count + 1
else:
# add new key and a count of 1 to dict
dict[string] = 1
Upvotes: 0
Reputation: 1078
This can easily be done with simple list looping and dict.get
method, though other efficient method exist.
lst = ['apple', 'orange', 'pears', 'pears', 'banana']
dict = {'orange': 4, 'apple':2, 'pears': 1}
for st in lst:
dict[st] = dict.get(st,0)+1
dict
{'orange': 5, 'apple': 3, 'pears': 3, 'banana': 1}
Upvotes: 1
Reputation: 1010
Your answer was almost correct:
for string in lst:
if string in dict.keys():
dict[string] += 1
else:
dict[string] = 1
This is assuming that a string you haven't seen yet starts with a value of 1, which seems to be the case given your output.
You could also remove the .keys(), as python will automatically check in the keys for the values you are looping on, hence:
for string in lst:
if string in dict:
dict[string] += 1
else:
dict[string] = 1
Upvotes: 1
Reputation: 117856
You can use collections.Counter
from collections import Counter
>>> lst = ['apple', 'orange', 'pears', 'pears', 'banana']
>>> d = {'orange': 4, 'apple':2, 'pears': 1}
>>> count = Counter(d)
>>> count
Counter({'orange': 4, 'apple': 2, 'pears': 1})
>>> count += Counter(lst)
>>> count
Counter({'orange': 5, 'pears': 3, 'apple': 3, 'banana': 1})
Upvotes: 1