How to check if a word-meaning pair is present in a dictionary?

Is there a smart pythonic way to check if there is an element (key, value) in a dict?

a={'a':1,'b':2,'c':3}
b={'a':1}
c={'a':2}

b in a:
--> True
c in a:
--> False
+4
source share
9 answers

Use the short circuiting property for and. Thus, if the left hand is false, then you will not get the KeyErrorvalue when checking.

>>> a={'a':1,'b':2,'c':3}
>>> key,value = 'c',3                # Key and value present
>>> key in a and value == a[key]
True
>>> key,value = 'b',3                # value absent
>>> key in a and value == a[key]
False
>>> key,value = 'z',3                # Key absent
>>> key in a and value == a[key]
False
+8
source

You checked this 2.7, not 2.x, so you can check if the tuple is in the dict viewitems:

(key, value) in d.viewitems()

Under the hood, it’s basically key in d and d[key] == value.

Python 3 viewitems items, items Python 2! , O (n) , , O (1).

+6
>>> a = {'a': 1, 'b': 2, 'c': 3}
>>> b = {'a': 1}
>>> c = {'a': 2}

, Python2 Python3

>>> all(k in a and a[k] == b[k] for k in b)
True
>>> all(k in a and a[k] == c[k] for k in c)
False

Python3

>>> b.items() <= a.items()
True
>>> c.items() <= a.items()
False

Python2

>>> b.viewitems() <= a.viewitems()
True
>>> c.viewitems() <= a.viewitems()
False
+3

:

dict.get, ( , )

>>> dict = {'Name': 'Anakin', 'Age': 27}
>>> dict.get('Age')
27
>>> dict.get('Gender', 'None')
'None'
>>>

-

get (, ) -   , , . , None, KeyError.

+2

, .items().

test = {'a': 1, 'b': 2}
print(('a', 1) in test.items())
>>> True
+1

get:

# this doesn't work if `None` is a possible value
# but you can use a different sentinal value in that case
a.get('a') == 1

try/except:

# more verbose than using `get`, but more foolproof also
a = {'a':1,'b':2,'c':3}
try:
    has_item = a['a'] == 1
except KeyError:
    has_item = False

print(has_item)

, items Python3 viewitems Python 2.7, , Python . .

0
   a.get('a') == 1
=> True
   a.get('a') == 2
=> False

None - :

{'x': None}.get('x', object()) is None
0

.get .

if my_dict.get('some_key'):
  # Do something

There is one caveat: if the key exists, but is false, then it will not pass the test, which may not be what you want. Keep in mind that this is rarely the case. Now the reverse problem is more frequent. This is used into check for a key. I often found this problem when reading csv files.

Example

# csv looks something like this:
a,b
1,1
1,

# now the code
import csv
with open('path/to/file', 'r') as fh:
  reader = csv.DictReader(fh) # reader is basically a list of dicts
  for row_d in reader:
    if 'b' in row_d:
      # On the second iteration of this loop, b maps to the empty string but
      # passes this condition statement, most of the time you won't want 
      # this. Using .get would be better for most things here. 
0
source

For python 3.x use if key in dict

See sample code

#!/usr/bin/python
a={'a':1,'b':2,'c':3}
b={'a':1}
c={'a':2}
mylist = [a, b, c]
for obj in mylist:
    if 'b' in obj:
        print(obj['b'])


Output: 2
0
source

Source: https://habr.com/ru/post/1619955/


All Articles