2

I am quite new to Python and want to know how to convert the below key->value pair dictionary to key-> [value] i.e my value is a list so that I can append more elements to the list. My dictionary is as follows:

{'Mississippi': '28', 'Oklahoma': '40', 'Delaware': '10', 'Minnesota': '27', 'Illinois': '17', 'Arkansas': '05', 'New Mexico': '35', 'Indiana': '18', 'Maryland': '24'}

How can I convert to:

{'Mississippi': ['28'], 'Oklahoma': ['40'], 'Delaware': ['10'], 'Minnesota': ['27'], 'Illinois': ['17'], 'Arkansas': ['05'], 'New Mexico': ['35'], 'Indiana': ['18'], 'Maryland': ['24']}

So I tried to do this:

dict_cntrycodes= {k: [v] for k,[v] in cntry_codes} 

But I am gettin ERROR: Too many values to unpack.

Any suggestions?

2 Answers 2

4
>>> testDict = {'Mississippi': '28', 'Oklahoma': '40', 'Delaware': '10', 'Minnesota': '27', 'Illinois': '17', 'Arkansas': '05', 'New Mexico': '35', 'Indiana': '18', 'Maryland': '24'}

>>> {k: [v] for k, v in testDict.items()}
{'Mississippi': ['28'], 'Oklahoma': ['40'], 'Delaware': ['10'], 'Minnesota': ['27'], 'Illinois': ['17'], 'Arkansas': ['05'], 'New Mexico': ['35'], 'Indiana': ['18'], 'Maryland': ['24']}

You are getting the too many values to unpack error since the keys in the first dictionary are strings and not lists. The following works.

>>> elem = "abc"
>>> [elem] = ['abc']

But, this gives an error.

>>> [elem] = "abc"

Traceback (most recent call last):
  File "<pyshell#64>", line 1, in <module>
    [elem] = "abc"
ValueError: too many values to unpack

This is because you are trying to unpack three elements ('a', 'b', 'c') to one element elem.

If you do this, the problem goes away

>>> [a, b, c] = "abc"
>>> print a, b, c
a b c
Sign up to request clarification or add additional context in comments.

Comments

1

if you want to edit your original dictionary, then do this.

d = {'Mississippi': '28', 'Oklahoma': '40', 'Delaware': '10', 'Minnesota': '27', 'Illinois': '17', 'Arkansas': '05', 'New Mexico': '35', 'Indiana': '18', 'Maryland': '24'}
for i in d: d[i] = [d[i]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.