0

如果这是一个重复的问题,我深表歉意,但我在任何地方都找不到任何类似的例子,所以寻求您的帮助。

lookup = {}

# These values will be filled by DB lookup service at runtime
# Maximum array length for category is unknown before program start 
# Format [Lookup Category], [Lookup Key], Lookup Id

lookup['name']['John'] = 1
lookup['name']['Jane'] = 2
lookup['name']['Joe'] = 3
lookup['gender']['Male'] = 1
lookup['gender']['Female'] = 2
lookup['country']['Japan'] = "jp"
lookup['country']['China'] = "ch"

print lookup['name']['Jane']
print lookup['gender']['Female']
print lookup['country']['China']
4

1 回答 1

6

你可能想要collections.defaultdict

例如

from collections import defaultdict

lookup = defaultdict(dict)
lookup['name']['John'] = 1
lookup['name']['Jane'] = 2
lookup['name']['Joe'] = 3
lookup['gender']['Male'] = 1
lookup['gender']['Female'] = 2
lookup['country']['Japan'] = "jp"
lookup['country']['China'] = "ch"

print lookup['name']['Jane']
print lookup['gender']['Female']
print lookup['country']['China']
于 2013-07-29T11:10:09.297 回答