Sometimes, while working with Python dictionaries, we can have a problem in which we need to flatten dictionary of key-value pair pairing the equal index elements together. This can have utilities in web development and Data Science domain. Lets discuss certain way in which this task can be performed.
Here's a Python program that takes in a list of key-value pairs and converts it into a flat dictionary:
def flatten_dict(kv_list): flat_dict = {} for kv in kv_list: if isinstance(kv, dict): for k, v in kv.items(): flat_dict.update({k: v}) else: flat_dict.update({kv[0]: kv[1]}) return flat_dict
The function flatten_dict
takes in a list of key-value pairs, where each key-value pair can either be a dictionary or a tuple containing two elements (key, value). It then iterates through the list, checking whether each element is a dictionary or a tuple.
If the element is a dictionary, the function iterates through the key-value pairs in the dictionary and updates the flat_dict
with each key-value pair. If the element is a tuple, the function updates the flat_dict
with the key-value pair in the tuple.
Finally, the function returns the flat_dict
, which contains all the key-value pairs from the original list flattened into a single dictionary.
Here's an example usage of the function:
kv_list = [{'a': 1, 'b': 2}, ('c', 3), {'d': 4}] flat_dict = flatten_dict(kv_list) print(flat_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
In this example, the kv_list
contains a dictionary, a tuple, and another dictionary. The flatten_dict
function converts this list into a flat dictionary with keys 'a'
, 'b'
, 'c'
, and 'd'
, and their corresponding values.
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.