Look up in dictionary
Tue Feb 01 2022 04:55:44 GMT+0000 (Coordinated Universal Time)
Saved by
@marcpio
# in operator allows to check whether a key is in a dictionary (appearing as value is not enough)
eng2sp = {'one':'uno', 'two':'dos', 'three':'tres'}
'one' in eng2sp
>> True
'uno' in eng2sp
>> False
# to see whether something appears as value, use method values(), which returns collection of values:
'uno' in eng2sp.values()
>> True
# dictionary method get() takes a key and a default value; if the key appears in the dict, get() returns the corresponding value; otherwise it returns the default value
h = {'a': 99}
h.get('a', 0)
>> 99
h.get('b', 0)
>> 0
# WHen using a dict in a for statement, it traverses its keys
for key in d:
print(key, d[key])
# to travers keys in sorted order, use function sorted():
for key in sorted(h):
print(key, d[key])
# the method items() returns a sequence of tuples, wehere each tuole is a key-value pair:
d = {'a':0, 'b':1, 'c':2}
for key, value in d.item():
print(key, value)
>> c 2
>> a 0
>> b 1
content_copyCOPY
Comments