简体   繁体   English

如何只为一个 Key 更新 Set in Dictionary? (Python)

[英]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'}}实际输出:{'b': {'1', '2'}, 'a': {'1', '2'}, 'c': {'1', '2'}}

Desired Output: {'a': {'1', '2'}, 'b': {'1'}, , 'c': {'1'}}所需输出:{'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

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'} .是一个字典,键a , b , c都映射到同一个集合对象{'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'}}

Instead of .update just assign:而不是.update只是分配:

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

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'}}

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

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