I want to extract values A, C, D and E (I don't need value_B, which is a number) from the following dictionary:
{'key1': [{'key_A': 'value_A', 'key_B': value_B},
{'key_A': 'value_C'},
{'key_A': 'value_D'},
{'key_A': 'value_E'}],
'key2': True}
Then I want to concatenate those values into a single string with a new line between each value. Like so:
string = ''
for value in values:
string += value + '\n'
Or maybe this:
string = ''
string = '\n'.join(values)
What I want is this:
string = 'value_A' + '\n' + 'value_C' + '\n' + 'value_D' + '\n' + 'value_E'
What's the best approach to do this? How would I go about doing it? I don't even know where to start.
Any help would be appreciated. Thank you.
While you could do this in a one liner, I'd recommend decomposing your problem into smaller sub-problems.
my_string = '\n'.join(e['key_A'] for e in my_dict['key1'])
You have a dictionary in which one of the keys contains a list of dicts. You want to end up with a string containing the value of 'key_A' from every dict in the list of dicts separated by '\n'.
To me the obvious steps are:
# Select the list of dicts from the parent dict
my_list_of_dicts = my_dict['key1']
# Select the 'key_A' value from each dict in the list
my_values = [e['key_A'] for e in my_list_of_dicts]
# Join the values together into a string separated by the '\n'
my_string = '\n'.join(my_values)
If you don't know what key to use until runtime, and you are confident that the first key will be the desired key. You can either derive the key in advance and store it or derive it for each individual dict.
# Derive the key in advance
# Get the first key of the first dict stored in my_dict['key1']
my_key = list(my_dict['key1'][0].keys())[0]
my_string = '\n'.join(e[my_key] for e in my_dict['key1'])
# Derive the first key for every dict
my_string = '\n'.join(e[list(e.keys()[0])] for e in my_dict['key1'])
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments