【问题标题】:How to extract a specific value from a dictionary in python如何从python中的字典中提取特定值
【发布时间】:2015-11-28 10:34:47
【问题描述】:

我想从 Python 中的谷歌距离矩阵 API 中提取距离。它返回的对象是一个python字典。

{
    'destination_addresses': [Mumbai, Maharashtra, India '],
        'origin_addresses': ['Powai, Mumbai, Maharashtra, India'],
        'rows': [{
            'elements': [{
                'distance': {
                    'text': u '47.1 km',
                    'value': 47086
                },
                'duration': {
                    'text': '1 hour 17 mins',
                    'value': 4628
                },
                'status': 'OK'
            }]
        }],
        'status': 'OK'
    }

我想从上面提取距离和持续时间。我用过

distance = my_distance["rows"]
for a in distance:
    result = a["elements"]
    print result

它给了我

[{
    u 'duration': {
        u 'text': u '1 hour 17 mins', u 'value': 4628
    }, u 'distance': {
        u 'text': u '47.1 km', u 'value': 47086
    }, u 'status': u 'OK'
}]

现在如何提取持续时间(1 小时 17 分钟)和距离(47.1 公里)及其对应值(4628 和 47086)

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    你可以这样做:

    print "time taken : ", d["rows"][0]["elements"][0]["duration"]["text"]
    print "distance : ", d["rows"][0]["elements"][0]["distance"]["text"]
    print "distance value : ", d["rows"][0]["elements"][0]["distance"]["value"]
    print "duration value : ", d["rows"][0]["elements"][0]["duration"]["value"]
    

    【讨论】:

      【解决方案2】:

      a["elements"] 包含一个字典列表。您可以对其进行迭代或通过索引值获取值。你可以在for 循环中试试这个:

      distance = result[0]['text']
      duration = result[1]['text']
      

      【讨论】:

        猜你喜欢
        • 2022-01-25
        • 2018-08-30
        • 2020-11-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-29
        • 2019-12-10
        • 1970-01-01
        相关资源
        最近更新 更多