簡體   English   中英

python append 值從字典中的字典中列出

[英]python append value to list from dictionary inside dictionary

我需要將 append 'rev' 和 'tta' 鍵和他的值放入新列表中。 我怎么能這樣做?

這是字典:

vl = {0: {'art': 5612306, 'rev': 3.0, 'report_id': 751233}, 1: {'art': 567206, 'tta': 2.8, 'report_id': 751233}}

我嘗試做什么並得到錯誤:

n_list = []
for elem in vl:
    n_list.append(vl[elem][1])

這是你想要的嗎?

>>> vl = {0: {'art': 5612306, 'rev': 3.0, 'report_id': 751233}, 1: {'art': 567206, 'tta': 2.8, 'report_id': 751233}}
>>> [item.get('rev', item.get('tta')) for item in vl.values()]
[3.0, 2.8]

像這樣試試

vl = {0: {'art': 5612306, 'rev': 3.0, 'report_id': 751233}, 1: {'art': 567206, 'tta': 2.8, 'report_id': 751233}}

n_list = []
for elem in vl:
    val = vl[elem]
    if 'rev' in val:
        n_list.append(val['rev'])
    elif 'tta' in val:
        n_list.append(val['tta'])

print(n_list)
#[3.0, 2.8]

你可以這樣寫,但是這段代碼只適合這種結構,

    n_list = []
    for elem in vl:
        n_list.append(vl[elem][tuple(vl[elem])[1]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM