Reputation: 49
cow = {
"data": [
{
"id": "1179640025492630",
"indicator": "google-analytics|UA-97996598-1",
"type": "API_KEY"
},
{
"id": "1469013519830038",
"indicator": "google-analytics|UA-96613605-2",
"type": "API_KEY"
},
{
"id": "1459958767410551",
"indicator": "google-analytics|UA-86399386-2",
"type": "API_KEY"
},
{
"id": "1507839102569000",
"indicator": "google-analytics|UA-89570367-2",
"type": "API_KEY"
},
{
"id": "1276736575767341",
"indicator": "google-analytics|UA-69774312-4",
"type": "API_KEY"
},
{
"id": "1292251910882451",
"indicator": "google-analytics|UA-93952538-3",
"type": "API_KEY"
}
],
"paging": {
"cursors": {
"after": "NQZDZD",
"before": "MAZDZD"
}
}
}
I want to extract the "id": "1179640025492630" from the data dictionary.
I have tried to use a for loop like:
for i in cow['data']:
for key,value in i:
if(i == 'id'):
print key,value
else:
pass
it gives me a value error like:
Traceback (most recent call last):
File "./dict.py", line 14, in <module>
for key,value in ['data']:
ValueError: too many values to unpack
And if I use .iteritems
I get an AttributeError
:
Traceback (most recent call last):
File "./dict.py", line 14, in <module>
for key,value in ['data'].iteritems:
AttributeError: 'list' object has no attribute 'iteritems'
Upvotes: 2
Views: 8452
Reputation: 123541
If all you want to do is print all values associated with the id
s:
for thing in cow["data"]:
print(thing["id"])
Output:
1179640025492630
1469013519830038
1459958767410551
1507839102569000
1276736575767341
1292251910882451
Upvotes: 3
Reputation: 4862
Or you can combine list and dictionary comprehension, which might be easier to process along the line.
result = [{k:v for k,v in dikt.items() if k == "id"} for dikt in cow['data']]
gives you
[{'id': '1179640025492630'}, {'id': '1469013519830038'}, {'id': '1459958767410551'}, {'id': '1507839102569000'}, {'id': '1276736575767341'}, {'id': '1292251910882451'}]
And you can print it out like so:
print "\n".join([i['id'] for i in result])
Upvotes: 0
Reputation: 896
If you want to exctract the id field, use a mapping function:
map(lambda item: ("id", item["id"]), cow["data"])
and you'll get a list of tuples (be aware that py3 map is lazy and you'll force evaluation to list).
Upvotes: 1
Reputation: 6360
If you want a cleaner solution that using nested for
loops, you can use python's map
function to iterate over all of the dictionaries in data
and only take the id
values.
>>> list(map(lambda d: 'id: {}'.format(d['id']), cow['data']))
['id: 1179640025492630', 'id: 1469013519830038', 'id: 1459958767410551', 'id: 1507839102569000', 'id: 1276736575767341', 'id: 1292251910882451']
Upvotes: 1