Reputation: 49
I'm new to Python and have (what I know to be a very simple) question.
Running Python 3.4.
I have a list that I need to iterate over and pull specific information out. Here is a sample (truncated, many thousands of items) of the list (called parts):
[{'state': 'DEAD',
'id': 'phwl',
'type_name': 'GAME',
'unit_structure': 'lattice',
'vendor': 'Downward',
'type_id': 'shiftable'
'weight': 'heavy'},
{'state': 'ALIVE',
'id': 'a06c5',
'type_name': 'BOARD',
'unit_structure': 'frame',
'vendor': 'Sniggles',
'weight': 'light'}]
I want to do this using a for loop where I pull just the value after the 'id'
key and print it to my console. A simple for loop looks like this:
for i in parts:
print(i)
This, of course, prints all the information in the parts list again, which isn't what I want.
So I need to do something like:
for i in parts:
i = 'id'
print(i)
This isn't correct because it just prints:
id
id
id
id
....etc
So I need to do something where I tell it "every time you see 'id'
, print the value after it, but I'm unsure how to structure that loop.
Can anyone give me some guidance?
Upvotes: 0
Views: 2458
Reputation: 82765
If I understood you correctly. You are looking for fetching a value using key from a dict.
Ex:
for i in parts:
print(i["id"]) #or print(i.get("id"))
Output:
phwl
a06c5
MoreInfo in Python Dictionaries
Upvotes: 2