user3144125
user3144125

Reputation: 59

Tuple from dict of dict in Python

i've a dict of dict in python, for getting a random value from the dict

words = {0:{"wake up": "aaaa"},
         1:{"look after": "bbbb"},
         2:{"turn on": "cccc"}
        }

i want extract the second dict (the values of a number key) from the dict words

(k, v) = words[random.randint(0, 22)]

but the error is thisone

ValueError: need more than 1 value to unpack

why i need another values?

Upvotes: 0

Views: 152

Answers (2)

Sunny Nanda
Sunny Nanda

Reputation: 2382

Summary: Method 3 is the most pythonic way to do it.

  1. Without any modification to the data structures, the following code will work for you:

    k, v = words[random.randint(0, 2)].items()[0]
    

    However, this is not the best (& pythonic) way to do it.

  2. If your inner dict always has a single key-value pair, then there is really no need to keep it as a dict. Rather, keep the inner data as a tuple.

    words = {0: ("wake up", "aaaa"),
        1:("look after", "bbbb"),
        2:("turn on", "cccc")
    }
    
    # Now, the following line should work fine
    k, v = words[random.randint(0, 2)]
    
  3. And If there is no restriction on the outer data structure either, then use list or tuple as follows:

    words = (
        ("wake up", "aaaa"),
        ("look after", "bbbb"),
        ("turn on", "cccc")
    )
    
    # Now, the random.choice can be used
    k, v = random.choice(words)
    

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1122012

You are accessing the dictionary with a key, which returns just the value:

value = words[random.randint(0, 22)]

but if your keys are all integers, you would be better off using a list instead:

words = [{"wake up": "aaaa"}, {"look after": "bbbb"}, {"turn on": "cccc"}]
value = random.choice(words)

and let random.choice() do all the hard work of picking one at random.

You can still use random.choice() with dictionary values too of course:

value = random.choice(list(words.values()))

would return a random value from the dictionary, and:

key, value = random.choice(list(words.items()))

would return a random (key, value) pair for you.

If you meant to extract the stored dictionary into a key and value, you'd have to extract just one key-value pair from that object; you cannot use tuple unpacking on a dictionary:

>>> key, value = {'foo': 'bar'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

but this works:

>>> key, value = next(iter({'foo': 'bar'}.items()))
>>> key, value
('foo', 'bar')

but perhaps you should be storing tuples instead of dictionaries if you wanted to extract a random key-value pair, or store the keys and values directly in the words dictionary.

Upvotes: 3

Related Questions