Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dictionary that maps strings to a set of strings?

I would like to be able to make a Python dictionary with strings as keys and sets of strings as the values. E.g.: { "crackers" : ["crunchy", "salty"] } It must be a set, not a list.

However, when I try the following:

  word_dict = dict()
  word_dict["foo"] = set()
  word_dict["foo"] = word_dict["foo"].add("baz")                                    
  word_dict["foo"] = word_dict["foo"].add("bang")

I get:

Traceback (most recent call last):
  File "process_input.py", line 56, in <module>
    test()
  File "process_input.py", line 51, in test
    word_dict["foo"] = word_dict["foo"].add("bang")
AttributeError: 'NoneType' object has no attribute 'add'

If I do this:

  word_dict = dict()
  myset = set()
  myset.add("bar")
  word_dict["foo"] = myset
  myset.add("bang")
  word_dict["foo"] = myset

  for key, value in word_dict:                                                       
      print key,                                                                
      print value

I get:

Traceback (most recent call last):
  File "process_input.py", line 61, in <module>
    test()
  File "process_input.py", line 58, in test
    for key, value in word_dict:
ValueError: too many values to unpack

Any tips on how to coerce Python into doing what I'd like? I'm an intermediate Python user (or so I thought, until I ran into this problem.)

like image 988
Ellie P. Avatar asked Feb 18 '10 02:02

Ellie P.


People also ask

How do you map a string to a list in Python?

We can also use the map() function to convert a list of strings to a list of numbers representing the length of each string element i.e. It iterates over the list of string and apply len() function on each string element. Then stores the length returned by len() in a new sequence for every element.

Can I use map on dictionary Python?

We can use the Python built-in function map() to apply a function to each item in an iterable (like a list or dictionary) and return a new iterator for retrieving the results. map() returns a map object (an iterator), which we can use in other parts of our program.

Can Python dictionary store strings?

The Python list stores a collection of objects in an ordered sequence. In contrast, the dictionary stores objects in an unordered collection. However, dictionaries allow a program to access any member of the collection using a key – which can be a human-readable string.

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.


2 Answers

set.add() does not return a new set, it modifies the set it is called on. Use it this way:

word_dict = dict()
word_dict["foo"] = set()
word_dict["foo"].add("baz")                                    
word_dict["foo"].add("bang")

Also, if you use a for loop to iterate over a dict, you are iterating over the keys:

for key in word_dict:
   print key, word_dict[key]

Alternatively you could iterate over word_dict.items() or word_dict.iteritems():

for key, value in word_dict.items():
   print key, value
like image 125
sth Avatar answered Oct 20 '22 20:10

sth


from collections import defaultdict

word_dict = defaultdict(set)
word_dict['banana'].add('yellow')
word_dict['banana'].add('brown')
word_dict['apple'].add('red')
word_dict['apple'].add('green')
for key,values in word_dict.iteritems():
    print "%s: %s" % (key, values)
like image 25
Jonathan Feinberg Avatar answered Oct 20 '22 20:10

Jonathan Feinberg