首页 > 解决方案 > 在 Python 中访问动态字典键

问题描述

我有下面的python字典(dict1),我可以通过这种方式访问​​值:

dict1['starters]['Chicken Biryani Type']['Please select']

'Chicken Biryani Type' 和 'Please Select' 键是动态生成的。在那种情况下我将如何访问这些,因为据我所知我不能使用索引。

字典 (Dict1)

{
    'starters': {
        'product_name': 'Papadam',
        'base_price': 3.0,
        'Chicken Biryani Type': {
            'Please select': [{
                'Chicken': 3.0
            }, {
                'Puree': 4.0
            }],
            'Please remove': [{
                'mayonnaise': 0.0
            }, {
                'ketchup': 0.0
            }]
        },
        'Papadam Type': {
            'Plain or Spicy': [{
                'Plain': 3.0
            }, {
                'Spicy': 5.0
            }]
        }
    }
}

任何帮助表示赞赏。


更新。字典是如何创建的:

dict1 = {}
for cat in category_list:
    cat_dic = {cat: {}}
    dict1.update(cat_dic)
    sliced_df2 = df[df.productCategoryName == cat ]
    product_type = sliced_df2.productTypeName.unique()
    for ptype in product_type:
        sliced_df3 = sliced_df2[sliced_df2.productTypeName == ptype ]
        product_name = sliced_df3.productName.unique()
        product_name_a = {"product_name": product_name[0]}
        base_price = {"base_price": sliced_df3['variant_price'].min()}
        dict1[cat].update(product_name_a)
        dict1[cat].update(base_price)

        product_type_dict = {ptype: {}}
        dict1[cat].update(product_type_dict)
        attribute_names = sliced_df3.attribute_name.unique()
        for item in attribute_names:
            attribute_dict = {item: []}
            dict1[cat][ptype].update(attribute_dict)
            sliced_df4 = sliced_df3[sliced_df3.attribute_name == item ]
            # for item in attribute_values:
            for index, row in sliced_df4.iterrows():
                ab = {row['attribute_value']: row['variant_price']}
                dict1[cat][ptype][item].append(ab)

标签: pythondictionary

解决方案


推荐阅读