user9185088
user9185088

Reputation:

Iteration in dictionary using python

I'm using python 3.8 and I have list

 { "A1":[{"id": 1,"name": "abc", "isdeleted":true},{"id":2,"name": "pqr", "isdeleted":false},{"id": 3,"name" : "xyz", "isdeleted":false}]}

I want to iterate in dictionary and get result like

X = [1,2,3]

Upvotes: 0

Views: 76

Answers (3)

Anjaneya varma
Anjaneya varma

Reputation: 76

We can a create a list of type dict like these, change the dict as below. After slice the list.

myDict = {"A1":[{"id": 1,"name": "abc", "isdeleted":true},{"id": 2,"name": "pqr", "isdeleted":false},{"id": 3,"name": "xyz", "isdeleted":false}]}

x=[]
for i in X["A1"]:
    x.append(X['id']) 
Print(x)

Upvotes: 0

Bruce Salcedo
Bruce Salcedo

Reputation: 192

*note also change your boolean values to big letter "T" or "F", True not true and False not false.

myDict = {"A1": [
                {"id": 1, "name": "abc", "isdeleted": True}, 
                {"id": 2, "name": "pqr", "isdeleted": False}, 
                {"id": 3, "name": "xyz", "isdeleted": False}
                ]
                }
x = []

for item in myDict["A1"]:
    x.append(item["id"])

print(x)

output [1, 2, 3]

or you can use the shorter way:

myDict = {"A1": [
                {"id": 1, "name": "abc", "isdeleted": True}, 
                {"id": 2, "name": "pqr", "isdeleted": False}, 
                {"id": 3, "name": "xyz", "isdeleted": False}
                ]
                }
x = [item['id'] for item in myDict['A1']]

print(x)

Upvotes: 1

Igor Rivin
Igor Rivin

Reputation: 4864

Why not [i["id"] for i in X]?

Upvotes: 4

Related Questions