0

人を保持する dict を考えてみましょう:

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

ディクショナリ内の場所へのパスは、値に書き込むためにどのように保存されますか?

# Set city (Existing field)
city_field = ['address', 'city']
person[city_field] = 'London'  // Obviously won't work!

# Set country (New field)
country_field = ['address', 'country']
person[city_country] = 'UK'  // Obviously won't work!

読み取り用の辞書値へのパスを保存する方法を以前に尋ねたことに注意してください。

4

2 に答える 2

1

タプルをインデックスとして使用します。

city_field = ('address', 'city')    
country_field = ('address', 'country')

使用法:

>>> person = {}
>>> city_field = ('address', 'city')    
>>> country_field = ('address', 'country')
>>> person[city_field] = 'Miami'
>>> person[country_field] = 'UK'
>>> person
{('address', 'country'): 'UK', ('address', 'city'): 'Miami'}
于 2013-11-07T15:00:55.450 に答える