Reputation: 13
I am looking to update nested dictionary values from a pandas dataframe, but currently it updates all nested dictionaries, not only the one required. Here is my current code -
import pprint
import pandas as pd
update_dict = [
[1, 10],
[1, 30],
[2, 20],
[2, 40],
]
update_df = pd.DataFrame(update_dict, columns=['list_one', 'list_two'])
list_one = [1, 2, 3, 4, 5]
list_two = [10, 20, 30, 40]
dictionary = {}
sub_dictionary = dict.fromkeys(list_two, 0)
for item in list_one:
dictionary[item] = sub_dictionary
for item in list_one:
sub_df = update_df[update_df['list_one'] == item]
sub_list = sorted(list(set(sub_df['list_two'].to_list())))
for sub_item in sub_list:
dictionary[item][sub_item] = 1
The original dictionary looks liek this -
{1: {10: 0, 20: 0, 30: 0, 40: 0},
2: {10: 0, 20: 0, 30: 0, 40: 0},
3: {10: 0, 20: 0, 30: 0, 40: 0},
4: {10: 0, 20: 0, 30: 0, 40: 0},
5: {10: 0, 20: 0, 30: 0, 40: 0}}
Currently the output looks like this -
{1: {10: 1, 20: 1, 30: 1, 40: 1},
2: {10: 1, 20: 1, 30: 1, 40: 1},
3: {10: 1, 20: 1, 30: 1, 40: 1},
4: {10: 1, 20: 1, 30: 1, 40: 1},
5: {10: 1, 20: 1, 30: 1, 40: 1}}
I would like the output to look like this -
{1: {10: 1, 20: 0, 30: 1, 40: 0},
2: {10: 0, 20: 1, 30: 0, 40: 1},
3: {10: 0, 20: 0, 30: 0, 40: 0},
4: {10: 0, 20: 0, 30: 0, 40: 0},
5: {10: 0, 20: 0, 30: 0, 40: 0}}
Any help would be greatly appreciated. Thank you
Upvotes: 1
Views: 285
Reputation: 61910
You are using the same sub_dictionary, just do:
dictionary = {}
for item in list_one:
dictionary[item] = dict.fromkeys(list_two, 0)
Output
{1: {10: 1, 20: 0, 30: 1, 40: 0},
2: {10: 0, 20: 1, 30: 0, 40: 1},
3: {10: 0, 20: 0, 30: 0, 40: 0},
4: {10: 0, 20: 0, 30: 0, 40: 0},
5: {10: 0, 20: 0, 30: 0, 40: 0}}
When you do:
dictionary = {}
sub_dictionary = dict.fromkeys(list_two, 0)
for item in list_one:
dictionary[item] = sub_dictionary
All the values from dictionary will point to the same dictionary, so when you update any of the values, the change is reflected across all values.
The provided answer will create a new dictionary for every value.
Upvotes: 1