Extract Subset of Key-Value Pairs from Dictionary

Extract a subset of key-value pairs from dictionary?

You could try:

dict((k, bigdict[k]) for k in ('l', 'm', 'n'))

... or in Python 3 Python versions 2.7 or later (thanks to Fábio Diniz for pointing that out that it works in 2.7 too):

{k: bigdict[k] for k in ('l', 'm', 'n')}

Update: As Håvard S points out, I'm assuming that you know the keys are going to be in the dictionary - see his answer if you aren't able to make that assumption. Alternatively, as timbo points out in the comments, if you want a key that's missing in bigdict to map to None, you can do:

{k: bigdict.get(k, None) for k in ('l', 'm', 'n')}

If you're using Python 3, and you only want keys in the new dict that actually exist in the original one, you can use the fact to view objects implement some set operations:

{k: bigdict[k] for k in bigdict.keys() & {'l', 'm', 'n'}}

How to understand a one-line code that extract subset dictionary with selected key and value pairs

In short python has comprehensions that can provide one liner for datatype construction using for loops.

Here, this is an example of dictionary comprehension.

{key: self._the_main_dict[key] for key in self._the_main_dict.keys() & {'E', 'O', 'L'}}

This code can be extended to:

output = dict()
for key in self._the_main_dict.keys() & {'E', 'O', 'L'}:
output[key] = self._the_main_dict[key]

output is the response provided by above dictionary comprehension.

self._the_main_dict.keys() & {'E', 'O', 'L'}. If you're confused on this. This is just an Intersection operation between two sets. Yeah! Sets and Venn diagram you used to study in mathematics :D

Python extract subset of key values from List of Dictionaries

Unfortunately, your expected output is not possible, as all dictionary keys must be unique. You could add all matching values to nested lists to have them be accessible:

list1=[{'t1':43, 't2':45, 't3':56, 't4':59, 't5':45, 't6':31}, {'t1':3, 't2':5, 't3':5, 't4':9}, {'t1':47, 't2':59, 't3':86, 't4':5}]
myks=['t1','t3']
newlist={}
for i in range(len(list1)):
for j in list1[i].keys():
if j in myks:
if j not in newlist:
newlist[j] = [list1[i][j]]
else:
newlist[j].append(list1[i][j])

print(newlist)

>>> {'t1': [43, 3, 47], 't3': [56, 5, 86]}

You can then reference these through list indexing:

print(newlist['t1'][0])
>>> 43

How to understand a one-line code that extract subset dictionary with selected key and value pairs

In short python has comprehensions that can provide one liner for datatype construction using for loops.

Here, this is an example of dictionary comprehension.

{key: self._the_main_dict[key] for key in self._the_main_dict.keys() & {'E', 'O', 'L'}}

This code can be extended to:

output = dict()
for key in self._the_main_dict.keys() & {'E', 'O', 'L'}:
output[key] = self._the_main_dict[key]

output is the response provided by above dictionary comprehension.

self._the_main_dict.keys() & {'E', 'O', 'L'}. If you're confused on this. This is just an Intersection operation between two sets. Yeah! Sets and Venn diagram you used to study in mathematics :D

Most efficient way to extract multiple key/value pairs from a list of dictionaries of dictionaries in Python?

You mention--The final desired data are the 'raw' values of 'avg', 'low', 'high' and 'numberOfAnalysts' within the first dictionary entry in dispersion_analyst_data_list_extract.

That can be accomplished with the following.

dispersion_analyst_data_list_extract = [{'avg': {'raw': 3.02, 'fmt': '3.02'}, 'low': {'raw': 2.5, 'fmt': '2.5'}, 'high': {'raw': 3.15, 'fmt': '3.15'}, 'yearAgoEps': {'raw': 0.91, 'fmt': '0.91'}, 'numberOfAnalysts': {'raw': 20, 'fmt': '20', 'longFmt': '20'}, 'growth': {'raw': 2.319, 'fmt': '231.90%'}}, {'avg': {'raw': 2.62, 'fmt': '2.62'}, 'low': {'raw': 2.36, 'fmt': '2.36'}, 'high': {'raw': 3.05, 'fmt': '3.05'}, 'yearAgoEps': {'raw': 2.92, 'fmt': '2.92'}, 'numberOfAnalysts': {'raw': 20, 'fmt': '20', 'longFmt': '20'}, 'growth': {'raw': -0.103, 'fmt': '-10.30%'}}, {'avg': {'raw': 10.14, 'fmt': '10.14'}, 'low': {'raw': 8.87, 'fmt': '8.87'}, 'high': {'raw': 10.68, 'fmt': '10.68'}, 'yearAgoEps': {'raw': 8.51, 'fmt': '8.51'}, 'numberOfAnalysts': {'raw': 26, 'fmt': '26', 'longFmt': '26'}, 'growth': {'raw': 0.192, 'fmt': '19.20%'}}, {'avg': {'raw': 11.67, 'fmt': '11.67'}, 'low': {'raw': 9.39, 'fmt': '9.39'}, 'high': {'raw': 13.08, 'fmt': '13.08'}, 'yearAgoEps': {'raw': 10.14, 'fmt': '10.14'}, 'numberOfAnalysts': {'raw': 26, 'fmt': '26', 'longFmt': '26'}, 'growth': {'raw': 0.15100001, 'fmt': '15.10%'}}, {'avg': {}, 'low': {}, 'high': {}, 'yearAgoEps': {}, 'numberOfAnalysts': {}, 'growth': {}}, {'avg': {}, 'low': {}, 'high': {}, 'yearAgoEps': {}, 'numberOfAnalysts': {}, 'growth': {}}]

# dispersion_analyst_data_list_extract[0] is the first dictionary
# we access its desired keys using a list comprehension of the first dictionary
desired_output = [dispersion_analyst_data_list_extract[0][k] for k in ['avg', 'low', 'high', 'numberOfAnalysts']]

print(desired_output)
# Out: [{'raw': 3.02, 'fmt': '3.02'},
{'raw': 2.5, 'fmt': '2.5'},
{'raw': 3.15, 'fmt': '3.15'},
{'raw': 20, 'fmt': '20', 'longFmt': '20'}]

Python: subset of key/value pairs of a dict determines the function to call

There isn't a switch function afaik, but you can define the combination->function mapping inside a dictionary and iterate over that to check which case applies.

If efficiency matters, you might even be able to find the relevant key inside the dict to have a faster lookuptime.

Here's the basic version:

combination_function_map = {
'combination_a': function_a,
'combination_b': function_b
}

for key, func in combination_function_map.items():
if config[key].items() <= data.items():
func()

Extract dictionary values from nested keys, leaving main key, then turn into list

Use a list comprehension over a.items(), use dict.values() to get the values, and then you can use unpacking (*) to get the desired lists.

>>> [[k, *v.values()] for k,v in a.items()]
[[1, 50, 33, 40], [2, 30, 22, 45], [3, 15, 11, 50]]


Related Topics



Leave a reply



Submit