Reputation: 35
Is it possible to map a string to a map in Python. For example, if I want a map that looks like:
mymap = { 'ABC': {'123' : 56}, 'DEF': {'456' : 92} }
Is this possible? How would I add a value to the map, or check the map to see what the value is of the 'inner map' if I am doing an iteration when mymap is empty (at the start of a loop, for example). Thanks!
Upvotes: 0
Views: 5861
Reputation: 2054
Yes it's possible. If you aren't sure is mymap
has elements and don't want to do a try except
you can use the dict.get(key, default)
method:
value = mymap.get('ABC', {}).get('123', None)
if values is not None:
# Found key 123 inside mymap['ABC']
else:
# mymap['123'] or mymap['123']['ABC'] doesn't exist
Upvotes: 0
Reputation: 1493
>>> from collections import defaultdict
>>> mymap = defaultdict(dict)
>>> mymap['ABC'] = {'123' : 56}
>>> mymap
defaultdict(<type 'dict'>, {'ABC': {'123': 56}})
can you try this snippet, hope this solves your purpose
Upvotes: 1