将元组转换为字典中的列表

Convert a tuple to a list in a dictionary

我的 GeoJSON 输出格式如下:

{'type': 'Point', 'coordinates': (0.00027777777777777827, 22.000138888888873)}

如何将 'coordinates' 的值从元组转换为列表,同时保持 'type' 不变?

我试过使用 {k: [list(ti) for ti in v] for k, v in geom.items()} 给定 其中 geom = geometry.mapping(geometry.Point(x, y)) 但它没有帮助。

我看到一个错误 'Float object is not iterable'

我正在使用 shapely 库

您只能将 'coordinates' 键更改为列表:

geom['coordinates'] = list(geom['coordinates'])

输出 :

{'type': 'Point', 'coordinates': [0.00027777777777777827, 22.000138888888873]}

可以直接转换如下:

a['coordinates'] = list(a['coordinates'])

其中 a 是你的命令。

非常简单的方法,通过Python控制台测试:

>>> d = {'type': 'Point', 'coordinates': (0.00027777777777777827, 22.000138888888873)}
>>>
>>> type(d)
<class 'dict'>
>>>
>>> d['coordinates']
(0.00027777777777777827, 22.000138888888873)
>>>
>>> type(d['coordinates'])
<class 'tuple'>
>>>
>>> list(d['coordinates'])
[0.00027777777777777827, 22.000138888888873]

最后,你只覆盖字典的内容:

>>> d['coordinates'] = list(d['coordinates'])