【发布时间】:2017-11-15 16:06:22
【问题描述】:
我是 Python 和字典的新手。使用 Python 3.6.1。我搜索了类似的问题,但其他人使用的解决方案似乎涉及具有不同键的字典,并且许多答案与旧版本的 Python 有关。任何帮助表示赞赏!
我有以下在打印时返回的字典列表:
[{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None},
{'Coordinate': array([None, None], dtype=object), 'Height': None}]
我想将以下列表中的值插入到上述字典列表中:
coordkeys = ['Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate', 'Coordinate']
coordvalues = [[44,33], [55,22], [77,66], [88,99], [77,11], [46,78], [44,33], [13,92], [21,69], [79,91]]
heightkeys = ['Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height', 'Height']
heightvalues = [333, 444, 555, 666, 777, 888, 999, 222, 2222, 3333]
我想从这些列表中将值插入到字典列表中。因此结果遵循以下模式: 第一个 valuelist 的第一个条目将对应于第二个 valuelist 的第一个值(两者都在同一个字典中)。 显然,如果可能的话,我不希望使用 coordkeys 和 heightkeys 列表。
为了说明最终结果的模式,使用两个列表中的所有值,最终结果开始如下:
[{'Coordinate': [44,33], 'Height': 333},
{'Coordinate': [55,22], 'Height': 444},
# And so on until the end of both lists
]
我尝试只使用一个列表,如下所示:
geographic_details = dict(list(zip(coordkeys, coordvalues)))
但是输出的打印只返回坐标值列表中的最后一个条目,而不是列表中的所有值:
{'Coordinate': [79, 91]}
所以显然只保留了最后一个键值对,因为有几个同名的键。 zip 或这种使用 zip 的方式似乎不是这里的方式。
编辑:
我尝试通过这样做从两个列表中添加,但似乎不允许这样做。:
最后一行代码遗漏了一个结束括号。现在我添加了它,它看起来像这样:
geographic_details = dict(list(zip(coordkeys, coordvalues), zip(heightkeys, heightvalues)))
但是返回一个新的错误:
TypeError: list() takes at most 1 argument (2 given)
【问题讨论】:
-
geographic_details = dict(list(zip(coordkeys, coordvalues), zip(heightkeys, heightvalues))) -
你在末尾缺少一个右括号。
-
感谢您指出这一点,现在已修复。现在出现新错误,请参阅编辑。
-
请不要在一个问题中逐步询问代码中的每个问题。在每篇文章中提出一个具体问题。
标签: python list dictionary