0

I have a list of dictionaries like this:

temp = [
    {
        "item": "apple",
        "id": 1
    },
    {
        "item": "ball",
        "id": 2
    },
    {
        "item": "cake",
        "id": 3
    }
]

I want two lists:

["apple", "ball", "cake"]
[1, 2, 3]

Can we do this using list comprehension?

I have done like this:

list_item=[]
list_id=[]
for val in temp:
    list_item.append(val["item"])
    list_id.append(val["id"])

2 Answers2

2

Use the dictionary key item to store values in l1 and id to store values in l2.

q = [
    {
        "item": "apple",
        "id": 1
    },
    {
        "item": "ball",
        "id": 2
    },
    {
        "item": "cake",
        "id": 3
    }
]

l1 = [dic['item'] for dic in q]
l2 = [dic['id'] for dic in q]

In a single loop :

l1,l2 = [],[]
for dic in q:
    l1.append(dic['item'])
    l2.append(dic['id'])
Suraj
  • 2,253
  • 3
  • 17
  • 48
0
x =  {"item": "apple","id": 1}
y = json.loads(x)
a[0]=y["item"]
b[0]=y["id"]

you can try like that

See this: https://www.w3schools.com/python/python_json.asp

zywy
  • 100
  • 7