简体   繁体   中英

list comprehension using dictionary entries

trying to figure out how I might be able to use list comprehension for the following:

I have a dictionary:

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

and I would like to create a list (let's call it "list") which is populated by each of the "tag" values of each key, ie

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

is there an efficient way to do this using list comprehension? i was thinking something like:

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

but obviously this doesn't quite work. any help appreciated!

Try this:

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']

You can sort the list afterwards if it matters.

If you have other key/value pairs in the inner dicts, apart from 'tag', you may want to specify the 'tag' keys, like this:

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

for the same result. If 'tag' is definitely always there, remove the if 'tag' in d[i] part.

As a side note, never a good idea to call a list 'list', since it's a reserved word in Python.

This is an extra step but gets the desired output and avoids using reserved words:

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()]

I would do something like this:

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]

It also sounds like you're trying to get some info out of JSON you might want to look into a tool like https://stedolan.github.io/jq/manual/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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