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 }] } } }
另外,这个字典的创建代码是基于DataFrame生成的:
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 index, row in sliced_df4.iterrows(): ab = {row['attribute_value']: row['variant_price']} dict1[cat][ptype][item].append(ab)
这是个很常见的动态字典访问问题,我给你几个实用的解决方案,从直接遍历到优化字典结构都有:
方法一:直接遍历动态键
既然键是动态生成的,我们可以通过过滤+遍历的方式定位目标值。以你的starters分类为例:
首先,先把分类下的固定键(product_name、base_price)排除,剩下的就是动态的产品类型键:
category_data = dict1['starters'] # 筛选出所有动态产品类型键 product_type_keys = [key for key in category_data.keys() if key not in ['product_name', 'base_price']] # 逐个遍历产品类型 for ptype_key in product_type_keys: ptype_data = category_data[ptype_key] # 再遍历该产品类型下的所有属性键(比如'Please select') for attr_key in ptype_data.keys(): target_value = ptype_data[attr_key] print(f"找到产品类型: {ptype_key}, 属性: {attr_key}, 对应值: {target_value}")
如果你知道动态键的特征(比如产品类型键都带"Type"),还能更精准筛选:
product_type_keys = [key for key in category_data.keys() if 'Type' in key]
方法二:从生成逻辑优化字典结构(更推荐)
看你的字典生成代码,是从DataFrame转换来的,其实可以在生成阶段就优化结构,让后续访问更清晰。比如把所有动态产品类型统一放到一个product_types键下,和固定的product_name、base_price分开:
修改后的生成代码如下:
dict1 = {} for cat in category_list: # 初始化分类结构,专门用product_types存动态产品类型 cat_dic = { cat: { 'product_name': None, 'base_price': None, 'product_types': {} } } 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和base_price(假设同分类下这些值统一) if dict1[cat]['product_name'] is None: dict1[cat]['product_name'] = sliced_df3.productName.unique()[0] dict1[cat]['base_price'] = sliced_df3['variant_price'].min() # 把产品类型放到product_types字典里 dict1[cat]['product_types'][ptype] = {} attribute_names = sliced_df3.attribute_name.unique() for item in attribute_names: dict1[cat]['product_types'][ptype][item] = [] sliced_df4 = sliced_df3[sliced_df3.attribute_name == item ] for index, row in sliced_df4.iterrows(): ab = {row['attribute_value']: row['variant_price']} dict1[cat]['product_types'][ptype][item].append(ab)
优化后,访问动态键就清晰多了:
# 获取当前分类下所有动态产品类型 all_product_types = dict1['starters']['product_types'].keys() # 遍历访问每个产品类型的属性 for ptype in all_product_types: all_attributes = dict1['starters']['product_types'][ptype].keys() for attr in all_attributes: value = dict1['starters']['product_types'][ptype][attr] # 在这里处理你的值即可
方法三:递归遍历整个字典(适合复杂结构)
如果你的字典层级可能更深,或者不确定动态键的位置,可以写一个递归函数遍历所有键值对,直接找到你需要的内容:
def traverse_dict(d, current_path=""): for key, value in d.items(): # 构建当前访问路径 new_path = f"{current_path}['{key}']" if current_path else f"'{key}'" if isinstance(value, dict): # 如果还是字典,继续递归遍历 traverse_dict(value, new_path) else: # 打印值和对应的访问路径 print(f"访问路径: dict1{new_path}, 值: {value}") # 调用函数遍历整个dict1 traverse_dict(dict1)
这个函数会输出所有值的完整访问路径,你可以直接用这些路径访问目标值,也可以在函数里加条件判断,比如只打印包含特定关键词的键对应的值。
内容的提问来源于stack exchange,提问作者Rutnet
相关产品推荐
相关产品推荐

