Dict has key from list
How can I determine if any of the开发者_运维百科 list elements are a key to a dict? The straight forward way is,
for i in myList:
if i in myDict:
return True
return False
but is there a faster / more concise way?
#!python
any(x in MyDict for x in MyList)
set(MyList).intersection(MyDict)
In addition to any(item in my_dict for item in my_list)
from @Ronny's answer:
any(map(my_dict.__contains__, my_list)) # Python 3.x
Or:
from itertools import imap
any(imap(my_dict.__contains__, my_list)) # Python 2.x
Measure relative performance
Cases to consider:
- Item from the start of list is in in dictionary.
- Item from the end of list is in dictionary.
- No items from the list are in dictionary.
Functions to compare (see main.py):
def mgag_loop(myDict, myList):
for i in myList:
if i in myDict:
return True
return False
def ronny_any(myDict, myList):
return any(x in myDict for x in myList)
def ronny_set(myDict, myList):
return set(myDict) & set(myList)
def pablo_len(myDict, myList):
return len([x for x in myList if x in myDict]) > 0
def jfs_map(my_dict, my_list):
return any(map(my_dict.__contains__, my_list))
def jfs_imap(my_dict, my_list):
return any(imap(my_dict.__contains__, my_list))
Results: mgag_loop()
is the fastest in all cases.
1. Item from the start of list is in in dictionary.
def args_key_at_start(n):
'Make args for comparison functions "key at start" case.'
d, lst = args_no_key(n)
lst.insert(0, n//2)
assert (n//2) in d and lst[0] == (n//2)
return (d, lst)
2. Item from the end of list is in dictionary.
def args_key_at_end(n):
'Make args for comparison functions "key at end" case.'
d, lst = args_no_key(n)
lst.append(n//2)
assert (n//2) in d and lst[-1] == (n//2)
return (d, lst)
3. No items from the list are in dictionary.
def args_no_key(n):
'Make args for comparison functions "no key" case.'
d = dict.fromkeys(xrange(n))
lst = range(n, 2*n+1)
assert not any(x in d for x in lst)
return (d, lst)
How to reproduce
Download main.py, make-figures.py, run python main.py
(numpy
, matplotlib
should be installed to create plots).
To change maximum size of input list, number of points to plot supply --maxn
, --npoints
correspondingly. Example:
$ python main.py --maxn 65536 --npoints 16
Assuming you are talking about python, an alternate method of doing this would be:
return len([x for x in myList if x in myDict]) > 0
Thank you all so much. I tested the performance of all the answers and the fastest was
return len([x for x in myList if x in myDict]) > 0
but I didn't try the "set" answer because I didn't see how to turn it into one line.
This was a popular answer to a related question:
>>> if all (k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
You can adapt it to check if any appears in the dictionary:
>>> if any(k in myDict for k in ("foo","bar")):
... print "Found one!"
...
Found one!
You can check against a list of keys:
>>> if any(k in myDict for k in myList):
... print "Found one!"
...
Found one!
精彩评论