首页 > 解决方案 > 如何在 Python 中将变量添加到字典中?

问题描述

我想在没有硬编码的情况下添加到我当前的字典中。我想通过根据某人正在工作的车站添加 -A 和 -B 来区分商店。

a_dict = {'A': [['LA', 'Sallys', 'Associate '], ['Hollywood', 'Tonys', 'Shelf'], ['Compton', 'Sally', 'Shelves']],'B': [['SAC', 'Sallys', 'Associate '], ['Townsland', 'Tonys', 'Shelf'], ['Compton', 'Tiffanys', 'Shelves']]}
    b_dict = {'Site':"", 'Store':"", 'Station':""}
    for key in a_dict:
        b_dict.update(a_dict) 
        #print(b_dict[key[0]])
        #print(value[0])
        output = [
    {'Site':val[0][0], 'Store':val[1][1], 'Station':val[2]}
    for vals in a_dict.values()
    for val in vals
    ]
        
        print(output)

代码当前打印出:

[{'Site': 'L', 'Store': 'a', 'Station': 'Associate '}, {'Site': 'H', 'Store': 'o', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'a', 'Station': 'Shelves'}, {'Site': 'S', 'Store': 'a', 'Station': 'Associate '}, {'Site': 'T', 'Store': 'o', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'i', 'Station': 'Shelves'}]
[{'Site': 'L', 'Store': 'a', 'Station': 'Associate '}, {'Site': 'H', 'Store': 'o', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'a', 'Station': 'Shelves'}, {'Site': 'S', 'Store': 'a', 'Station': 'Associate '}, {'Site': 'T', 'Store': 'o', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'i', 'Station': 'Shelves'}]

但我希望它打印出来:

[{'Site': 'L', 'Store': 'a-A', 'Station': 'Associate '}, {'Site': 'H', 'Store': 'o-B', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'a-B', 'Station': 'Shelves'}, {'Site': 'S', 'Store': 'a-A', 'Station': 'Associate '}, {'Site': 'T', 'Store': 'o-B', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'i-B', 'Station': 'Shelves'}]
[{'Site': 'L', 'Store': 'a-A', 'Station': 'Associate '}, {'Site': 'H', 'Store': 'o-B', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'a-B', 'Station': 'Shelves'}, {'Site': 'S', 'Store': 'a-A', 'Station': 'Associate '}, {'Site': 'T', 'Store': 'o-B', 'Station': 'Shelf'}, {'Site': 'C', 'Store': 'i-B', 'Station': 'Shelves'}]

因此,如果员工是货架或货架,那么商店将是-B,如果不是,则商店应该是-A。

标签: pythondictionarykeyorganization

解决方案


干得好。

a_dict = {'A': [['LA', 'Sallys', 'Associate '], ['Hollywood', 'Tonys', 'Shelf'], ['Compton', 'Sally', 'Shelves']],'B': [['SAC', 'Sallys', 'Associate '], ['Townsland', 'Tonys', 'Shelf'], ['Compton', 'Tiffanys', 'Shelves']]}
b_dict = {'Site':"", 'Store':"", 'Station':""}
for key in a_dict:
    b_dict.update(a_dict) 
    #print(b_dict[key[0]])
    #print(value[0])
    output = [
{'Site':val[0][0], 'Store':val[1][1], 'Station':val[2]}
for vals in a_dict.values()
for val in vals
]
    for x in output:
        if x["Station"] in ("Shelf","Shelves"):
            x["Store"] += "-B"
        else:
            x["Store"] += "-A"
    print(output)

你在问题的最后一行说了你需要做什么。


推荐阅读