Mark McGown
Mark McGown

Reputation: 1095

How do I update Set in Dictionary for only one Key? (Python)

I am having a difficult time seeing my mistake. I'm trying to just update the set of values for one specific key in a dictionary at a time, except every key is getting updated.

final_df = dict.fromkeys({'a','b','c'}, {'1'})
final_df['a'].update({'1','2'})
final_df

Actual Output: {'b': {'1', '2'}, 'a': {'1', '2'}, 'c': {'1', '2'}}

Desired Output: {'a': {'1', '2'}, 'b': {'1'}, , 'c': {'1'}}

Also tried:

final_df = dict.fromkeys({'a','b','c'}, {'1'})
final_df['a'] = final_df['a'].update({'1','2'})
final_df

Upvotes: 1

Views: 153

Answers (3)

adrtam
adrtam

Reputation: 7211

This is a simple mistake. What you produce here:

final_df = dict.fromkeys({'a','b','c'}, {'1'})

is a dictionary that with the keys a, b, c all maps to the same set object {'1'}. Then, all subsequent mutation on the set like you did:

final_df['a'].update({'1','2'})

will mutate all mappings as they are all point to the same set object.

To solve this problem, you can consider dictionary comprehension, which will replicate the set object for each key:

>>> final_df = {k:{'1'} for k in {'a','b','c'}}
>>> final_df
{'c': {'1'}, 'a': {'1'}, 'b': {'1'}}
>>> final_df['a'].update({'2','3'})
>>> final_df
{'c': {'1'}, 'a': {'1', '3', '2'}, 'b': {'1'}}

Upvotes: 2

Mark McGown
Mark McGown

Reputation: 1095

It looks like I needed union instead of update.

final_df = dict.fromkeys({'a','b','c'}, {'1'})
final_df['a'] = final_df['a'].union({'2'})
final_df

Output:

{'b': {'1'}, 'a': {'1', '2'}, 'c': {'1'}}

Upvotes: 0

wasif
wasif

Reputation: 15478

Instead of .update just assign:

final_df = dict.fromkeys({'a','b','c'}, {'1'})
final_df['a'] = {'1','2'}
print(final_df)

Upvotes: 1

Related Questions