在 python 字典中将值从一个键转移到另一个键
Shifting values from one key to another key in python dictionary
我有以下字典 (Geojson):
'properties': {
'fill': '#ffffff', 'fill-opacity': 1, 'stroke': '#ffffff',
'stroke-opacity': 1, 'stroke-width': 1.5, 'title': '0.00 m',
'time': '2000-01-31'
}
通过将某些值移动到属性中的新键,将其变成如下所示的最简单方法是什么。
'properties': {
'style': {
'fill': '#ffffff', 'fill-opacity': 1, 'stroke': '#ffffff',
'stroke-opacity': 1, 'stroke-width': 1.5, 'title': '0.00 m'
},
'time': '2000-01-31'
}
}
任何反馈都会有所帮助。
谢谢
您可以 pop time
并像这样构建一个新的字典:
properties = {
'fill': '#ffffff', 'fill-opacity': 1, 'stroke': '#ffffff',
'stroke-opacity': 1, 'stroke-width': 1.5, 'title': '0.00 m',
'time': '2000-01-31'
}
time = properties.pop('time')
new_properties = {'style': properties, 'time':time}
print(new_properties)
# {'style': {'fill': '#ffffff', 'fill-opacity': 1, 'stroke': '#ffffff',
# 'stroke-opacity': 1, 'stroke-width': 1.5, 'title': '0.00 m'},
# 'time': '2000-01-31'}
假设原始数据在一个dict中(如果有key和value就一定是dict),同样得到想要的结果:
from pprint import pprint
start = {
'properties': {
'fill': '#ffffff', 'fill-opacity': 1, 'stroke': '#ffffff',
'stroke-opacity': 1, 'stroke-width': 1.5, 'title': '0.00 m',
'time': '2000-01-31'
}
}
result = {
'properties': {
'style': start['properties'],
'time': start['properties'].pop('time')
},
}
pprint(result)
结果:
{'properties': {'style': {'fill': '#ffffff',
'fill-opacity': 1,
'stroke': '#ffffff',
'stroke-opacity': 1,
'stroke-width': 1.5,
'title': '0.00 m'},
'time': '2000-01-31'}}
我有以下字典 (Geojson):
'properties': {
'fill': '#ffffff', 'fill-opacity': 1, 'stroke': '#ffffff',
'stroke-opacity': 1, 'stroke-width': 1.5, 'title': '0.00 m',
'time': '2000-01-31'
}
通过将某些值移动到属性中的新键,将其变成如下所示的最简单方法是什么。
'properties': {
'style': {
'fill': '#ffffff', 'fill-opacity': 1, 'stroke': '#ffffff',
'stroke-opacity': 1, 'stroke-width': 1.5, 'title': '0.00 m'
},
'time': '2000-01-31'
}
}
任何反馈都会有所帮助。 谢谢
您可以 pop time
并像这样构建一个新的字典:
properties = {
'fill': '#ffffff', 'fill-opacity': 1, 'stroke': '#ffffff',
'stroke-opacity': 1, 'stroke-width': 1.5, 'title': '0.00 m',
'time': '2000-01-31'
}
time = properties.pop('time')
new_properties = {'style': properties, 'time':time}
print(new_properties)
# {'style': {'fill': '#ffffff', 'fill-opacity': 1, 'stroke': '#ffffff',
# 'stroke-opacity': 1, 'stroke-width': 1.5, 'title': '0.00 m'},
# 'time': '2000-01-31'}
假设原始数据在一个dict中(如果有key和value就一定是dict),同样得到想要的结果:
from pprint import pprint
start = {
'properties': {
'fill': '#ffffff', 'fill-opacity': 1, 'stroke': '#ffffff',
'stroke-opacity': 1, 'stroke-width': 1.5, 'title': '0.00 m',
'time': '2000-01-31'
}
}
result = {
'properties': {
'style': start['properties'],
'time': start['properties'].pop('time')
},
}
pprint(result)
结果:
{'properties': {'style': {'fill': '#ffffff',
'fill-opacity': 1,
'stroke': '#ffffff',
'stroke-opacity': 1,
'stroke-width': 1.5,
'title': '0.00 m'},
'time': '2000-01-31'}}