Home > Mobile >  Python appending values from one dictionary to another with the same keys
Python appending values from one dictionary to another with the same keys

Time:12-14

Evening,

I'm trying to append another set of values to the same set of keys in a dictionary.

currently, I pull the some postcode attributes from an api which stores the request in a dictionary and returns the outcome in a dataframe. But If I wanted to return another postcode attributes from the same api how would I append the values from it to the same dictionary so they appear as a second row in the dataframe.

current bit of code:

import requests
import pandas as pd

url = "https://api.getthedata.com/postcode/ST87HL"
req = requests.get(url)
data = req.json()
entries = data["data"]

df = pd.DataFrame([entries])
print(df)

Really appreciate all the help, thank you.

CodePudding user response:

If you have your postcodes in the list, iterate over this list and append result into another list. As last step, create a DataFrame from this list:

import requests
import pandas as pd

postcodes = ["ST87HL", "ST87EZ"]

all_data = []
for p in postcodes:
    url = "https://api.getthedata.com/postcode/{}".format(p)
    req = requests.get(url)
    data = req.json()
    entries = data["data"]
    all_data.append(entries)


df = pd.DataFrame(all_data)
print(df)

Prints:

  postcode status usertype  easting  northing  positional_quality_indicator  country   latitude  longitude postcode_no_space postcode_fixed_width_seven postcode_fixed_width_eight postcode_area postcode_district postcode_sector outcode incode
0  ST8 7HL   live    small   388982    357799                             1  England  53.117254  -2.166072            ST87HL                    ST8 7HL                   ST8  7HL            ST               ST8           ST8 7     ST8    7HL
1  ST8 7EZ   live    small   389017    358349                             1  England  53.122198  -2.165568            ST87EZ                    ST8 7EZ                   ST8  7EZ            ST               ST8           ST8 7     ST8    7EZ
  • Related