如何使用 Python 集并将字符串作为字典值添加到其中

2022-01-17 00:00:00 python dictionary set

问题描述

我正在尝试创建一个将值作为 Set 对象的字典.我想要一组与唯一引用关联的唯一名称).我的目标是尝试创造类似的东西:

I am trying to create a dictionary that has values as a Set object. I would like a collection of unique names associated with a unique reference). My aim is to try and create something like:

目标:

Dictionary[key_1] = set('name')    
Dictionary[key_2] = set('name_2', 'name_3')

添加到 SET:

Dictionary[key_2].add('name_3')

但是,使用 set 对象将 name 字符串分解为预期的字符,如 这里.我试图使字符串成为一个元组,即 set(('name'))Dictionary[key].add(('name2')),但这确实无法按要求工作,因为字符串被拆分为字符.

However, using the set object breaks the name string into characters which is expected as shown here. I have tried to make the string a tuple i.e. set(('name')) and Dictionary[key].add(('name2')), but this does not work as required because the string gets split into characters.

是通过列表将字符串添加到集合以阻止它被分解成字符的唯一方法

Is the only way to add a string to a set via a list to stop it being broken into characters like

'n', 'a', 'm', 'e'

任何其他想法将不胜感激.

Any other ideas would be gratefully received.


解决方案

你可以像@larsmans 解释的那样写一个单元素元组,但是很容易忘记结尾的逗号.如果您只使用列表作为 set 构造函数和方法的参数,则可能不太容易出错:

You can write a single element tuple as @larsmans explained, but it is easy to forget the trailing comma. It may be less error prone if you just use lists as the parameters to the set constructor and methods:

Dictionary[key_1] = set(['name'])    
Dictionary[key_2] = set(['name_2', 'name_3'])

Dictionary[key_2].add(['name_3'])

都应该按照您的预期工作.

should all work the way you expect.

相关文章