简体   繁体   English

如何修改字典中的值?

[英]How to modify a value in a dictionary?

I want to add on to my current dictionary without hardcoding.我想在没有硬编码的情况下添加到我当前的字典中。 I want to distinguish between stores by adding -A and based on the station someone is working in.我想通过添加 -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]])

This is what the code currently prints out这是代码当前打印的内容

[['LA', 'Sallys', 'Associate '], ['Hollywood', 'Tonys', 'Shelf'], ['Compton', 'Sally', 'Shelves']]
[['SAC', 'Sallys', 'Associate '], ['Townsland', 'Tonys', 'Shelf'], ['Compton', 'Tiffanys', 'Shelves']]

But I want it to print out this但我想让它打印出来

[['LA', 'Sallys', 'Associate '], ['Hollywood', 'Tonys', 'Shelf'], ['Compton', 'Sally', 'Shelves-A']]
[['SAC', 'Sallys', 'Associate '], ['Townsland', 'Tonys', 'Shelf'], ['Compton', 'Tiffanys', 'Shelves-A']]

In my answer there are a few assumptions and changes in order to work.在我的回答中,有一些假设和更改才能起作用。 With not hardcoded you probably mean that the key value can change, right?如果没有硬编码,您可能意味着键值可以更改,对吧? I changed the b_dict values to empty lists in order to add all stores, sites etc. later on.我将 b_dict 值更改为空列表,以便稍后添加所有商店、站点等。 Here is my solution.这是我的解决方案。 Really hope this is what you are looking for, because it was hard to understand your question.真的希望这是您正在寻找的,因为很难理解您的问题。

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':[]}



a_dict = [(x[0], x[1] ,x[2]+"-"+k) for k, v in a_dict.items() for x in v]

for obj in a_dict:
    for i, key in enumerate(b_dict.keys()):
        b_dict[key] += [obj[i]]

print(a_dict)
# [('LA', 'Sallys', 'Associate-A'), ('Hollywood', 'Tonys', 'Shelf-A'), ('Compton', 'Sally', 'Shelves-A'), ('SAC', 'Sallys', 'Associate-B'), ('Townsland', 'Tonys', 'Shelf-B'), ('Compton', 'Tiffanys', 'Shelves-B')]

print(b_dict)
# {'Site': ['LA', 'Hollywood', 'Compton', 'SAC', 'Townsland', 'Compton'], 'Store': ['Sallys', 'Tonys', 'Sally', 'Sallys', 'Tonys', 'Tiffanys'], 'Station': ['Associate-A', 'Shelf-A', 'Shelves-A', 'Associate-B', 'Shelf-B', 'Shelves-B']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM