簡體   English   中英

pythonic從nest字典中調用特定鍵/值的方法

[英]pythonic way of calling specific keys/values from a nest dictionary

什么是從嵌套字典中獲取特定鍵/值的pythonic方法?

例如,我想從這個嵌套字典中獲取奇數的所有dict值:

nested_dict = {'bulldog': {'type': 3}, 'cat': {'type': 4}, 'yorkie': {'type': 11}, 'pitbull': {'type': 8}}

輸出應該如下所示:

new_dict = {'bulldog': {'type': 3}, 'yorkie': {'type': 11}}

另外,如果我想只拉出具有奇數值的嵌套鍵,在這種情況下輸出將如下所示:

new_dict2 = {'type': 3, 'type': 11}

這是一個相當直接的使用詞典理解,如:

碼:

new_dict = {k: v for k, v in nested_dict.items() if v['type'] % 2 != 0}

測試代碼:

nested_dict = {'bulldog': {'type': 3}, 'cat': {'type': 4},
               'yorkie': {'type': 11}, 'pitbull': {'type': 8}}

new_dict = {k: v for k, v in nested_dict.items() if v['type'] % 2 != 0}
print(new_dict)

結果:

{'bulldog': {'type': 3}, 'yorkie': {'type': 11}}

暫無
暫無

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

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