Python嵌套字典理解返回空字典(Python nested dictionary comprehension returns empty dictionaries)

编程入门 行业动态 更新时间:2024-10-28 21:21:24
Python嵌套字典理解返回空字典(Python nested dictionary comprehension returns empty dictionaries)

我正在使用字典理解来提取嵌套值。 我有以下代码(作为示例):

d = {1: 'a', 2: 'b', 3: 'c'} e = {4: 'd', 5: 'e', 6: 'f'} f = {7: 'g', 8: 'h', 9: 'i'} # stick them together into another dict data_dict = {'one': d, 'two': e, 'three': f} #say we're looking for the key 8 output = {outer_key: {inner_key: inner_value for inner_key, inner_value in outer_value.items() if inner_key == 8} for outer_key, outer_value in data_dict.items()} output = {'one': {}, 'three': {8: 'h'}, 'two': {}}

我需要做些什么来获得JUST'三'及其价值? 我不想返回空的比赛。

谢谢

I'm using dictionary comprehension to pull out a nested value. I have the following code (as a sample):

d = {1: 'a', 2: 'b', 3: 'c'} e = {4: 'd', 5: 'e', 6: 'f'} f = {7: 'g', 8: 'h', 9: 'i'} # stick them together into another dict data_dict = {'one': d, 'two': e, 'three': f} #say we're looking for the key 8 output = {outer_key: {inner_key: inner_value for inner_key, inner_value in outer_value.items() if inner_key == 8} for outer_key, outer_value in data_dict.items()} output = {'one': {}, 'three': {8: 'h'}, 'two': {}}

what do I need to do to get JUST 'three' and its value? I don't want to return empty matches.

thx

最满意答案

像这样的东西:

>>> {k: {8: v[8]} for k, v in data_dict.items() if 8 in v} {'three': {8: 'h'}}

Something like this:

>>> {k: {8: v[8]} for k, v in data_dict.items() if 8 in v} {'three': {8: 'h'}}

更多推荐

本文发布于:2023-07-31 10:20:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1341960.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字典   嵌套   nested   Python   dictionary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!