How can I ask for a key of a subkey in a dictionary in Python? -
if have dictionary in dictionary, how can ask key in constant time? example:
def get_hobby(hobby): d = {'an' : {'hobby': "paintball", 'age' : 22}, 'jef' : {'hobby' : "football", 'age': 24}, 'jos' : {'hobby': "paintball", 'age' : 46}} assert get_hobby("paintball") == ['an', 'jos'] this doesn't work:
return d.keys[hobby]
use list comprehension:
return [name name, props in d.items() if props['hobby'] == hobby] d.items() gives sequence of (key, value) pairs, value nested dictionary. list comprehension filters these matching hobby variable nested 'hobby' key, producing list of names filter test returns true.
you cannot ask keys in constant time, because number variable.
demo:
>>> def get_hobby(hobby): ... d = {'an' : {'hobby': "paintball", 'age' : 22}, 'jef' : {'hobby' : "football", 'age': 24}, 'jos' : {'hobby': "paintball", 'age' : 46}} ... return [name name, props in d.items() if props['hobby'] == hobby] ... >>> get_hobby("paintball") ['jos', 'an'] note returned list of keys in arbitrary order, because dictionaries have no set ordering. cannot test list against list , expect equal every single time, because lists have order. exact order depends on python hash seed , insertion , deletion history of dictionary.
you may want return set instead; sets not have ordering either , better reflect nature of matching keys returned:
return {name name, props in d.items() if props['hobby'] == hobby} after assertion become:
assert get_hobby("paintball") == {'an', 'jos'}
Comments
Post a Comment