python - 在 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)
解决方案
推荐阅读
- flutter - 是否可以在 Flutter 的函数中将类作为参数传递?
- laravel - 如何将多个关联数组条目发布到邮递员以及如何在 laravel 控制器中访问它
- java - Springboot JPA 将列连接为实体
- android - 异常的 WRAP_CONTENT 行为
- google-roads-api - Google Roads API“未找到请求的实体”
- regex - 使用额外参数和更改函数名称的批量重构函数调用
- c# - 如何使用 [HttpPut] 动词访问 WebApi 控制器中的 HttpParams
- php - 如何在 laravel Eloquent 中获取包含多个表的整个对象?(数据库结构已更新)
- python - Python-Pandas:如何通过一列中有多少相似值来创建排序数据框?
- python - Bot无法连接语音通道