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?

4

2 回答 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']}

由于第一个字典中的键是字符串而不是列表,因此您得到的值太多而无法解包错误。以下作品。

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

但是,这给出了一个错误。

>>> [elem] = "abc"

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

这是因为您试图将三个元素 ( 'a', 'b', 'c') 解压缩为一个元素elem

如果你这样做,问题就会消失

>>> [a, b, c] = "abc"
>>> print a, b, c
a b c
于 2013-07-23T17:33:49.360 回答
1

如果您想编辑您的原始字典,请执行此操作。

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]]
于 2013-07-23T17:51:32.900 回答