python - 从列表中填充字典值

标签 python list dictionary

我正在尝试用 Python 构建字典。代码如下所示:

dicti = {}
keys = [1, 2, 3, 4, 5, 6, 7, 8, 9]
dicti = dicti.fromkeys(keys)

values = [2, 3, 4, 5, 6, 7, 8, 9]

如何使用列表填充字典的值?是否有一些内置功能?

结果应该是这样的:

dicti = {1:2,2:3,3:4,4:5,5:6,6:7,7:8,8:9}

最佳答案

如果您有两个列表keys相应的 values:

keys = [1, 2, 3, 4, 5, 6, 7, 8, 9]
values = [2, 3, 4, 5, 6, 7, 8, 9]
dicti = dict(zip(keys, values))

dicti 现在是 {1: 2, 2: 3, 3: 4, 4: 5, 5: 6, 6: 7, 7: 8, 8: 9}

关于python - 从列表中填充字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11468027/

相关文章:

Python正则表达式匹配多次

ios - 在 iOS 中不使用 NSDictionary 的情况下具有多种类型的 Swift 字典数组

c# - 在 C# 2.0 中同步两个 IList 的最佳算法

C++ 包含类的排序列表

C# 将静态类放入字典中

python - 使用 dict 重新映射 pandas 列中的值,保留 NaN

python - Pytest monkeypatch 不适用于导入的函数

python - Pandas 根据另一列跟踪每月价格变化

python - Scipy-interp2d 返回的函数自动对输入参数进行排序,但不符合预期

python - 将新项目 append 到列表时出现问题