3

ちょっと複雑な質問がありますが、その問題の根底に到達できないようです。Python 辞書内の位置に対応するキーのリストがあります。位置の値を動的に変更できるようにしたいと思います(リスト内のキーで見つかりました)。

例えば:

listOfKeys = ['car', 'ford', 'mustang']

私も辞書を持っています:

DictOfVehiclePrices = {'car':
                          {'ford':
                              {'mustang': 'expensive',
                               'other': 'cheap'},
                           'toyota':
                              {'big': 'moderate',
                               'small': 'cheap'}
                          },
                       'truck':
                          {'big': 'expensive',
                           'small': 'moderate'}
                      }

私のリストを介して、どうすれば の値を動的に変更できますDictOfVehiclePrices['car']['ford']['mustang']か?

私の実際の問題では、辞書を介してキーのリストをたどり、最後の位置で値を変更する必要があります。これを動的に (ループなどで) どのように行うことができますか?

ご協力ありがとうございました!:)

4

5 に答える 5

4

とを使用reduceoperator.getitemます。

>>> from operator import getitem
>>> lis = ['car', 'ford', 'mustang']

更新値:

>>> reduce(getitem, lis[:-1], DictOfVehiclePrices)[lis[-1]] = 'cheap'

フェッチ値:

>>> reduce(getitem, lis, DictOfVehiclePrices)
'cheap'

Python 3ではfunctoolsモジュールreduceに移動したことに注意してください。

于 2013-11-12T07:41:59.507 に答える
1
print reduce(lambda x, y: x[y], listOfKeys, dictOfVehiclePrices)

出力

expensive

値を変更するには、

result = dictOfVehiclePrices
for key in listOfKeys[:-1]:
    result = result[key]

result[listOfKeys[-1]] = "cheap"
print dictOfVehiclePrices

出力

{'car': {'toyota': {'small': 'cheap', 'big': 'moderate'},
 'ford': {'mustang': 'cheap', 'other': 'cheap'}},
 'truck': {'small': 'moderate', 'big': 'expensive'}}
于 2013-11-12T07:43:14.157 に答える
1

非常に単純なアプローチは次のとおりです。

DictOfVehiclePrices[listOfKeys[0]][listOfKeys[1]][listOfKeys[2]] = 'new value'
于 2013-11-12T07:41:26.300 に答える
0

@Joel Cornett による優れたソリューションがあります。

Joelメソッドに基づいて、次のように使用できます。

def set_value(dict_nested, address_list):
    cur = dict_nested
    for path_item in address_list[:-2]:
        try:
            cur = cur[path_item]
        except KeyError:
            cur = cur[path_item] = {}
    cur[address_list[-2]] = address_list[-1]

DictOfVehiclePrices = {'car':
                      {'ford':
                          {'mustang': 'expensive',
                           'other': 'cheap'},
                       'toyota':
                          {'big': 'moderate',
                           'small': 'cheap'}
                      },
                   'truck':
                      {'big': 'expensive',
                       'small': 'moderate'}
                  }

set_value(DictOfVehiclePrices,['car', 'ford', 'mustang', 'a'])

print DictOfVehiclePrices
  • 標準出力:

{'car': {'toyota': {'small': 'cheap', 'big': 'moderate'}, 'ford': {'mustang': 'a', 'other': 'cheap'}} , 'トラック': {'小さい': '普通', '大きい': '高い'}}

于 2013-11-12T07:53:20.220 に答える