简体   繁体   中英

How to iterate through dictionary in a list

I tried to extract out the information of distance, duration, and status of the list of dictionary below and I am stuck

So far I have

distance = [{u'distance': {u'text': u'248 mi', u'value': 398525},
  u'duration': {u'text': u'3 hours 59 mins', u'value': 14346},
  u'status': u'OK'},
 {u'distance': {u'text': u'2,306 mi', u'value': 3711303},
  u'duration': {u'text': u'1 day 9 hours', u'value': 120030},
  u'status': u'OK'}]
## What is the distance (in miles) between location x and location y?
for i in range(len(distance)):
    for key in distance[i]:
        print(distance[i][key])
  • I'm assuming you want the value indicated under "distance->duration->value"? You could directly access it via indexing
  • meantime, you could iterate through lists and dictionaries directly without using range(len(<array>))

my suggestion below:

distance = [{u'distance': {u'text': u'248 mi', u'value': 398525},
  u'duration': {u'text': u'3 hours 59 mins', u'value': 14346},
  u'status': u'OK'},
 {u'distance': {u'text': u'2,306 mi', u'value': 3711303},
  u'duration': {u'text': u'1 day 9 hours', u'value': 120030},
  u'status': u'OK'}]
## What is the distance (in miles) between location x and location y?
for d in distance:
    print(d['distance']['value'])

output

398525
3711303

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM