简体   繁体   中英

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_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. 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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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