繁体   English   中英

使用字典条目进行列表理解

[英]list comprehension using dictionary entries

试图弄清楚我如何能够对以下内容使用列表理解:

我有一本字典:

dict = {}
dict ['one'] = {"tag":"A"}
dict ['two'] = {"tag":"B"}
dict ['three'] = {"tag":"C"}

我想创建一个列表(我们称之为“列表”),该列表由每个键的每个“标签”值填充,即

['A', 'B', 'C']

有没有一种有效的方法来使用列表理解呢? 我在想类似的东西:

list = [x for x in dict[x]["tag"]]

但显然这不太有效。 任何帮助表示赞赏!

尝试这个:

d = {'one': {'tag': 'A'},
     'two': {'tag': 'B'},
     'three': {'tag': 'C'}}

tag_values = [d[i][j] for i in d for j in d[i]]

>>> print tag_values
['C', 'B', 'A']

您可以在以后对列表进行排序。

如果内部字典中还有其他键/值对,除了“标签”之外,您可能还需要指定“标签”键,如下所示:

tag_value = [d[i]['tag'] for i in d if 'tag' in d[i]]

对于相同的结果。 如果'tag'始终存在,请删除if 'tag' in d[i]部分中if 'tag' in d[i]

附带说明一下,将list称为“列表”绝不是一个好主意,因为它是Python中的保留字。

这是一个额外的步骤,但可以获得所需的输出,并且避免使用保留字:

d = {}
d['one'] = {"tag":"A"}
d['two'] = {"tag":"B"}
d['three'] = {"tag":"C"}
new_list = []
for k in ('one', 'two', 'three'):
    new_list += [x for x in d[k]["tag"]]

print(new_list)

您可以尝试以下方法:

[i['tag'] for i in dict.values()]

我会做这样的事情:

untransformed = {
    'one': {'tag': 'A'},
    'two': {'tag': 'B'},
    'three': {'tag': 'C'},
    'four': 'bad'
}
transformed = [value.get('tag') for key,value in untransformed.items() if isinstance(value, dict) and 'tag' in value]

听起来您还想尝试从JSON中获取一些信息,您可能想研究一下https://stedolan.github.io/jq/manual/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM