我如何转换自:
{'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
答案 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}