fmalaussena fmalaussena -4 years ago 63
JSON Question

Get all same key/value pairs of a JSON

I'm getting a dict (well, actually, a

) which basically looks like this

'a_list' :
{'key': 'value1', 'foo': 'bar1'},
{'key': 'value2', 'foo': 'bar2', 'sup': 'dope'}
{'key': 'value3'}

I'm interested in getting
in a list.

I know I can do this this way :

output_list = []
for i in my_dict["a_list"]:

But there's gotta be a more efficient way ?

Something like
or something.

Answer Source

That's not a JSON, it is a Python dictionary.

You can boost performance (a bit) by using the following list comprehension:

output_list = [ x['key'] for x in my_dict['a_list'] ]

You can't do this (much) more efficiently, since you will have to loop over the elements, to obtain a list of these elements.

The only other way to do it is lazily, by for instance using a map(..):

output_list = map(lambda x : x['key'],my_dict['a_list'])

But then you do not generate a list, but a generator. Eventually it will take the same time (if you need all the elements). But the generator is constructed fast (because the mapping is postponed).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download