python - 在值为单个整数的字典中将它们更改为列表

标签 python dictionary

为了简单起见,我的字典看起来像:

data ={"a": 12, "b": 13, "c": 22, "d": 33}

我有很大的字典。将键值对中的所有值转换为包含单个整数的列表的最有效方法是什么

我已经尝试过

for key in data:
    data[key] = list(data[key])

给我:

TypeError:'int' object not iterable.

这是否意味着我无法将单个整数转换为列表?

我可以通过以下方式获得所需的输出:

for key in data:
    lst = []
    lst.append(data[key])
    data[key] = lst

但感觉有一种更有效的方法。

所需输出:

  data ={"a": [12], "b": [13], "c": [22], "d": [33]}

最佳答案

按如下方式使用字典理解:

data = {key: [value] for key, value in data.items()}

运行示例:

>>> data ={"a":12, "b":13, "c":22, "d":33}
>>> data = {key: [value] for key, value in data.items()}
>>> data
{'a': [12], 'b': [13], 'c': [22], 'd': [33]}

我还使用 ipython 来查看我的解决方案或@Selcuk 哪种解决方案更有效,结果如下:

In [1]:
%%timeit
data ={"a":12, "b":13, "c":22, "d":33}
data = {key: [value] for key, value in data.items()}
1.05 µs ± 18.9 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In[2]:
%%timeit
data ={"a":12, "b":13, "c":22, "d":33}
data.update((k, [v]) for k, v in data.items())
1.61 µs ± 34.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

关于python - 在值为单个整数的字典中将它们更改为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58177792/

相关文章:

php - Python 没有正确重启 linux 进程

dictionary - "map"在计算机科学中的起源

python - 如何将具有一列的 csv 文件转换为 Python 中的字典?

IOS Swift 从 [String : [AnotherKindOfDictionary] ] ( ) 的字典中读取数据

javascript - Flask 中的动态散列链接

python - 预填充 Flask-WTForm IntegerField

python - 如何从 openCV 中提取 X 或元组值 - findContours where Y=39

python - python中闭环曲线内的面积

python - 从字典中排除重复值并相应地增加 'qty' 字段

C# - Dictionary<int, Dictionary<int, string>> 排序抛出 System.ArgumentException