python - 如何在 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。
解决方案
干得好。
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)
你在问题的最后一行说了你需要做什么。
推荐阅读
- asp.net-core - 每天上午 12 点和下午 12 点在 .net 核心中使用 Quartz 作业调度程序
- arrays - 如何在 Golang 中返回一个未知类型的数组?
- asp.net-mvc - 使用 jquery.validation.js 时提交按钮不发布数据
- notifications - 推送通知 - Acumatica/亚马逊
- python - 根据开始和停止列对数据框进行分组
- python-3.x - 提供任意数量的参数
- html - 如何使用 flexbox 添加下边距?
- github - GitHub Actions 工件检索
- c# - 如何从文本框中检索输入的值
- php - 带有范围的 Elasticsearch 过滤器,我应该使用 SUM 而不是项目计数吗?