将值从dict转换为字典中的list:value是type list to value是type dictionary

时间:2018-05-24 15:14:58

标签: python

我如何转换自:

{'a': [2], 'b': [2], 'c': [1], 'd': [1]}

{'a': 2, 'b': 2, 'c': 1, 'd': 1}

我试过了:

for key, value in numbersOfFollowersDict.items():
    numbersOfFollowersDict[key] = dict(value)
print(numbersOfFollowersDict)

但出现错误:

    numbersOfFollowersDict[key] = dict(value)
TypeError: cannot convert dictionary update sequence element #0 to a sequence

3 个答案:

答案 0 :(得分:3)

您可以在字典理解中使用解包:

import logging
import argparse
import time
import os
import sys
import json

输出:

d = {'a': [2], 'b': [2], 'c': [1], 'd': [1]}
new_d = {a:b for a, [b] in d.items()}

答案 1 :(得分:3)

您可dict comprehension在这里

>>> d = {'a': [2], 'b': [2], 'c': [1], 'd': [1]}
>>> output = {k: v[0] for k, v in d.items()}
{'a': 2, 'c': 1, 'b': 2, 'd': 1}

答案 2 :(得分:1)

使用dict()

d = {'a': [2], 'b': [2], 'c': [1], 'd': [1]}
d = dict((k, v[0]) for k,v in d.items())
print(d)

<强>输出:

{'a': 2, 'c': 1, 'b': 2, 'd': 1}