Home > Mobile >  How to convert a list of dictionaries to a list?
How to convert a list of dictionaries to a list?

Time:03-16

How to convert a list of dictionaries to a list?

Here is what I have:

{
    "sources": [
        {
            "ID": "6953",
            "VALUE": "https://address-jbr.ofp.ae"
        },
        {
            "ID": "6967",
            "VALUE": "https://plots.ae"
        },
        {
            "ID": "6970",
            "VALUE": "https://dubai-creek-harbour.ofp.ae"
        }]}

Here is what I want it to look like:

({'6953':'https://address-jbr.ofp.ae','6967':'https://plots.ae','6970':'https://dubai-creek-harbour.ofp.ae'})

CodePudding user response:

This is indeed very straightforward:

data = {
    "sources": [
        {
            "ID": "6953",
            "VALUE": "https://address-jbr.ofp.ae"
        },
        {
            "ID": "6967",
            "VALUE": "https://plots.ae"
        },
        {
            "ID": "6970",
            "VALUE": "https://dubai-creek-harbour.ofp.ae"
        }]
}

Then:

data_list = [{x["ID"]: x["VALUE"]} for x in data["sources"]]

Which is the same as:

data_list = []
for x in data["sources"]:
    data_list.append({
        x["ID"]: x["VALUE"]
    })

EDIT: You said convert to a "list" in the question and that confused me. Then this is what you want:

data_dict = {x["ID"]: x["VALUE"] for x in data["sources"]}

Which is the same as:

data_dict = {}
for x in data["sources"]:
    data_dict[x["ID"]] = x["VALUE"]

P.S. Seems like you're asking for answers to your course assignments or something here, which is not what this place is for.

CodePudding user response:

A solution using pandas


import pandas as pd

data = {
    "sources": [
        {"ID": "6953", "VALUE": "https://address-jbr.ofp.ae"},
        {"ID": "6967", "VALUE": "https://plots.ae"},
        {"ID": "6970", "VALUE": "https://dubai-creek-harbour.ofp.ae"},
    ]
}

a = pd.DataFrame.from_dict(data["sources"])
print(a.set_index("ID").T.to_dict(orient="records"))

outputs to:

[{'6953': 'https://address-jbr.ofp.ae', '6967': 'https://plots.ae', '6970': 'https://dubai-creek-harbour.ofp.ae'}]

CodePudding user response:

this should work.

Dict = {
    "sources": [
        {
            "ID": "6953",
            "VALUE": "https://address-jbr.ofp.ae"
        },
        {
            "ID": "6967",
            "VALUE": "https://plots.ae"
        },
        {
            "ID": "6970",
            "VALUE": "https://dubai-creek-harbour.ofp.ae"
        }]}

# Store all the keys here
value_LIST = []
for item_of_list in Dict["sources"]:
    for key, value in item_of_list.items():
        value_LIST.append(value)
  • Related