How to use Python sets and add strings to it in as a dictionary value(如何使用 Python 集并将字符串作为字典值添加到其中)
问题描述
我正在尝试创建一个将值作为 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.
这篇关于如何使用 Python 集并将字符串作为字典值添加到其中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 Python 集并将字符串作为字典值添加到其中
基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 包装空间模型 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
