Reputation: 439
If I have the following dictionary and list, is there a way that I can looking is the items in the list are contained within the keys of the dictionary?
I tried inverting the dictionary and looking up the values, but keys cant have the same values so it messes up the schema.
('dict', {'2D 4D': 0, '1B 2C': 0})
('list', ['2B', '2D', '3D', '4D', '4A'])
so when you ask something similar to
if key in dict: //if '2D' is in dict
dict[key]+=1 //{'2D 4D': 1}
Upvotes: 1
Views: 160
Reputation: 593
If keys of the dict are assumed to be in the way of having a space in the middle, you can use this also.
a = {'2D 4D': 0, '1B 2C': 0}
b = ['2B', '2D', '3D', '4D', '4A']
for i in a.keys():
a[i]=len(set(i.split()).intersection(b))
OUTPUT:
{'2D 4D': 2, '1B 2C': 0}
Upvotes: 0
Reputation: 5958
You can compare each dict key entry to all in your list. For clean code purposes, don't use dict
/list
as var names:
mdict = {'2D 4D': 0, '1B 2C': 0}
mlist = ['2B', '2D', '3D', '4D', '4A']
for k in mdict.keys():
for e in mlist:
if e in k:
mdict[k] += 1
# mdict:
{'1B 2C': 0, '2D 4D': 2}
If you have a huge list of words or dictionary entries, this will be slow. I suggest implementing a trie of your list entries and iterate with that, which will reduce the complexity from O(M*N) to O(N+M).
Upvotes: 2