存储字典值的路径

时间:2013-11-06 12:36:36

标签: python dictionary path

如何将dict dict中的值存储到路径?例如,我们可以轻松地将name值的路径存储在变量name_field中:

person = {}
person['name'] = 'Jeff Atwood'
person['address'] = {}
person['address']['street'] = 'Main Street'
person['address']['zip'] = '12345'
person['address']['city'] = 'Miami'

# Get name
name_field = 'name'
print( person[name_field] )

如何存储city值的路径?

# Get city
city_field = ['address', 'city']
print( person[city_field] )  // Obviously won't work!

4 个答案:

答案 0 :(得分:5)

你可以这样做:

path = ('address', 'city')
lookup = person
for key in path:
    lookup = lookup[key]

print lookup
# gives: Miami

如果路径的一部分不存在,这将引发KeyError

如果path由一个值组成,例如('name',),它也会有用。

答案 1 :(得分:3)

您可以使用reduce功能执行此操作

print reduce(lambda x, y: x[y], city_field, person)

<强>输出

Miami

答案 2 :(得分:1)

使用Simeon(和Unubtu删除的答案)的另一种方法是创建自己的dict类,定义一个额外的方法:

class mydict(dict):
    def lookup(self, *args):
        tmp = self
        for field in args:
            tmp = tmp[field]
        return tmp

person = mydict()
person['name'] = 'Jeff Atwood'
person['address'] = {}
person['address']['street'] = 'Main Street'
person['address']['zip'] = '12345'
person['address']['city'] = 'Miami'

print(person.lookup('address', 'city'))
print(person.lookup('name'))
print(person.lookup('city'))

导致:

Miami
Jeff Atwood
Traceback (most recent call last):
  File "look.py", line 17, in <module>
    print(person.lookup('city'))
  File "look.py", line 5, in lookup
    tmp = tmp[field]
KeyError: 'city'

您可以根据thefourtheye的建议缩短循环次数。如果你想要真正喜欢,你可以覆盖像__get__这样的私有方法,以允许像person['address', 'city']这样的情况,但事情可能会变得棘手。

答案 3 :(得分:1)

这是另一种方式 - 与Simeon Visser的行为完全相同

from operator import itemgetter
pget = lambda map, path: reduce(lambda x,p: itemgetter(p)(x), path, map)

使用您的示例数据:

person = {
  'name': 'Jeff Atwood',
  'address': {
    'street': 'Main Street',
    'zip': '12345',
    'city': 'Miami',
  },
}

pget(person, ('address', 'zip')) # Prints '12345'
pget(person, ('name',))          # Prints 'Jeff Atwood'
pget(person, ('nope',))          # Raises KeyError