遍历字典python列表 [英] looping through list of dictionaries python

查看:72
本文介绍了遍历字典python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问列表中的字典,但似乎无法让我的for循环获取键,然后获取值.

I'm trying to access a dictionary within a list and cannot seem to get my for loop to get the key, then the value.

我在这里放置了一张图片,以便于我解释.

I've placed an image herein so that its easy for me to explain.

所以您可以看到,我想导航到 currency = AUD 并将余额值分配给一个变量,将其称为 aud_balance

so you can see, I would like to navigate to currency = AUD and assign the balance value to a variable, call it aud_balance

for curr in result_bal_qr:
    for k in curr: 
        if curr[k] == 'AUD':

我似乎无法获取密钥 AUD .所以我正式被困住了.

I cannot seem to get the key AUD. so I'm officially stuck.

我试图在列表等中搜索字典,但是没有我的问题的例子,或者甚至可能我理解的问题是错误的(很有可能)

I've tried to search for dictionary inside of lists etc but no examples of my problem, or maybe even understood my problem wrong (highly likely)

感谢您的帮助.

推荐答案

您有字典列表.您想在迭代过程中遍历列表,但又不想遍历每个字典本身.您只想查看其 currency 键.所以:

You have a list of dicts. You want to iterate over the list as you are doing, but you don't want to iterate over each dict itself; you just want to check its currency key. So:

for curr in result_bal_qrp:
    if curr['currency'] == 'AUD':
        print(curr['balance'])

注意,如果要多次遍历此列表以查找不同的货币,则可能值得将其转换为简单的货币余额法则:

Note, if you're going to be iterating over this list multiple times to find different currencies, it may be worth converting it to a simple dict of currency to balance:

curr_dict = {d['currency']: d['balance'] for d in result_bal_qrp}

现在您可以执行 curr_dict ['AUD'] 来获取澳大利亚余额.

and now you can do curr_dict['AUD'] to get the Australian balance.

这篇关于遍历字典python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆