简体   繁体   中英

How to merge 2 different keys and combine their values as a list for JSON Object in python

I have a JSON object/python dictionary like this:

{  
"trip_id": 19121027,
"Latitude": "21.160284",
"Longitude": "72.772457",
"Speed": "46.00"
}

I want to combine the latitude and longitude parts as "Location" like:

{  
"trip_id": 19121027,
"Location":["21.160284","72.772457"],
"Speed": "46.00"
}

How can I do this?

data1 = {  
"trip_id": 19121027,
"Latitude": "21.160284",
"Longitude": "72.772457",
"Speed": "46.00"
}

data2 = {
"trip_id": data1["trip_id"],
"Location": [data1["Latitude"], data1["Longitude"]],
"Speed": data1["Speed"]
}

If you want to modify the dictionary in situ then you could do this:

dict_ = {
    "trip_id": 19121027,
    "Latitude": "21.160284",
    "Longitude": "72.772457",
    "Speed": "46.00"
}

for k in 'Latitude', 'Longitude':
    if v := dict_.get(k):
        dict_.setdefault('Location', []).append(v)
        del dict_[k]

print(dict_)

If you want a new dictionary then:

new_dict = {}

for k, v in dict_.items():
    if k in {'Latitude', 'Longitude'}:
        new_dict.setdefault('Location', []).append(v)
    else:
        new_dict[k] = v

Output:

{'trip_id': 19121027, 'Speed': '46.00', 'Location': ['21.160284', '72.772457']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM