[英]Pythonic way to extract specific values from a dictionary based on a subset of keys
[英]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.