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

Time:07-02

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?

CodePudding user response:

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"]
}

CodePudding user response:

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']}
  • Related