Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Python sets and add strings to it in as a dictionary value

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:

AIM:

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

Adding to SET:

Dictionary[key_2].add('name_3') 

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.

like image 905
12avi Avatar asked Jul 09 '14 12:07

12avi


People also ask

Can I add string in set Python?

Adding Strings to Python Sets An interesting note about appending strings to Python sets is that they can be appended using both the . add() and .

Does set () work on strings?

We can convert a string to setin Python using the set() function. Parameters : Any iterable sequence like list, tuple or dictionary. Returns : An empty set if no element is passed. Non-repeating element iterable modified as passed as argument.

How do you assign a string to a dictionary in Python?

To convert a Python string to a dictionary, use the json. loads() function. The json. loads() is a built-in Python function that converts a valid string to a dict.

What is set () Python?

Python set() Function The set() function creates a set object. The items in a set list are unordered, so it will appear in random order.


2 Answers

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.

like image 156
Duncan Avatar answered Sep 23 '22 01:09

Duncan


('name') is not a tuple. It's just the expression 'name', parenthesized. A one-element tuple is written ('name',); a one-element list ['name'] is prettier and works too.

In Python 2.7, 3.x you can also write {'name'} to construct a set.

like image 23
Fred Foo Avatar answered Sep 22 '22 01:09

Fred Foo