我是Python和字典的新手。使用python3.6.1。我在google上搜索过类似的问题,但其他人使用的解决方案似乎涉及到具有不同键的词典,而且许多答案都与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的第一个值(两者都在同一个字典中结束)。 显然,如果可能的话,我不想使用坐标键和高度键列表。你知道吗
要清除最终结果将具有的模式,以及两个列表中的所有值,最终结果如下开始:
[{'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)
你想要这样的东西吗?你知道吗
输出:
假设列表大小相等,
map
函数看起来是创建所需数据结构的最优雅的方法。你知道吗相关问题 更多 >
编程相关推荐