Reputation: 155
I have a list of dictionaries and I have a solution, described below:
[{"A1":"B1", "C1":"D1"},{"A2":"B2", "C2":"D2"},....]
Expected output would be a dictionary like this
{
"B1":"D1",
"B2":"D2",
...
}
My current procedure is get one dictionary and create a 2 entries dict to a single one
input:
{"A1":"B1", "C1":"D1"}
output:
{"B1":"D1"}
where the "A1" and "C1" is inside my method configureable:
def method(input_dictionary, default_key_from_dict, default_value_from_dict):
single_dictionary[input_dictionary[default_key_from_dict]] = input_dictionary[default_value_from_dict]
later I perform the following ones:
def function(dict_list):
single_key_value_dictionary_list = list(map(convert_two_entries_dictionary_to_one_by_value, dict_list))
global_dict = reduce(lambda a, b: dict(a, **b), single_key_value_dictionary_list)
return global_dict
I ask myself if there is some better solution for this, I have the generator idea in my mind but I am not sure if it is worth to think about it? Any remarks on this?
UPDATE There are only 2 keys in each entry of the list as dictionary. 2 keys only.
BR Peter
Upvotes: 1
Views: 41
Reputation: 442
You can use something about this:
dict1 = {"A1":"B1", "C1":"D1"}
it = iter(dict1.values())
list1 = list(zip(it, it))
print(list1)
Upvotes: 0
Reputation: 20669
From the comments since you always have only 2 keys. You can use dict.update
.
inp=[{"A1":"B1", "C1":"D1"},{"A2":"B2", "C2":"D2"}]
out={}
for d in inp:
out.update((d.values(),))
out
# {'B1': 'D1', 'B2': 'D2'}
Upvotes: 1