35

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.

2
  • 4
    On my computer (python 2.7.6), set.add does not break the string (while the set constructor does), so why don't you just create an empty set and add the string? Commented Jul 9, 2014 at 12:57
  • Dictionary[Key_1] = Set(['name_1']) --> input originally as as a list, then Dictionary[Key_1].add('name_2') --> no need for a input as a list seems to work and solve this. I then have a Set object from the onset. Thanks for all the suggestions/help. Commented Jul 9, 2014 at 13:43

2 Answers 2

29

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I find that when I use Dictionary.add['name_3'] after, I get an exception (unhashable type: 'list'). The only solution I found was therafter to use .add('name-3') --> Not now as a single list (but only for the Set constuctor).
Please read what I wrote: .add(['name_3']) is not the same as .add['name_3']
22

('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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.