I have a dictionary with the following structure:
{('key1','key2'): 50, ('key3','key4'): 70, ('key1','key5'): 90.....}
I want to count in my dictionary the number of times 'key1' for example appears as the first word in the key tuple.
I started writing the below mentioned code but could not think further:
count = 0
leng = 0
i = 0
for key1,key2 in range(1,len(bigrams)):
count = count +1
leng = leng + (bigrams.get((key1,key2),0))
print(count)
print(leng)
Any suggestion as to how should I proceed ?
from collections import defaultdict
der = {('key1','key2'): 50, ('key3','key4'): 70, ('key1','key5'): 90}
b = defaultdict(int)
for item, ler in der:
b[item] += 1
print b ## defaultdict(int, {'key1': 2, 'key3': 1})
print b['key1'] ## [2]
I'd use sum()
with a generator expression to iterate over the keys, testing each one in turn:
bigrams = {('key1','key2'): 50, ('key3','key4'): 70, ('key1','key5'): 90}
def number_of_times_key_appears_as_first_word(key, dictionary):
return sum(k[0] == key for k in dictionary)
assert number_of_times_key_appears_as_first_word('key1', bigrams) == 2
assert number_of_times_key_appears_as_first_word('key3', bigrams) == 1
assert number_of_times_key_appears_as_first_word('key2', bigrams) == 0
You can use collections.Counter
to count each part of the keys as the following:
from collections import Counter
dic = {('key1','key2'): 50, ('key3','key4'): 70, ('key1','key5'): 90}
keys_0 = Counter(key[0] for key in dic.keys())
keys_1 = Counter(key[1] for key in dic.keys())
# keys_0 = Counter({'key1': 2, 'key3': 1})
# keys_1 = Counter({'key2': 1, 'key4': 1, 'key5': 1})
You can type cast counter object to a dict if you want by using dict(Counter(...))
Below one gives the required count:
dict1 = {('key1','key2'): 50, ('key3','key4'): 70, ('key1','key5'): 90, ('key3','key1'): 90}
count = 0
for keys in dict1.keys():
if 'key1' in keys:
if (keys[0] == 'key1'):
count = count + 1
print count
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.