Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split that dictionary into keys and values into different lists. Let’s discuss the different ways we can do this.
Method #1: Using built-in functions
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
# Python code to demonstrate# to split dictionary# into keys and values # initialising _dictionaryini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'} # printing iniial_dictionaryprint("intial_dictionary", str(ini_dict)) # split dictionary into keys and valueskeys = ini_dict.keys()values = ini_dict.values() # printing keys and values separatelyprint ("keys : ", str(keys))print ("values : ", str(values)) |
Output:
intial_dictionary {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'}
keys : dict_keys(['a', 'b', 'c'])
values : dict_values(['akshat', 'bhuvan', 'chandan'])
Method #2: Using zip()
# Python code to demonstrate# to split dictionary# into keys and values # initialising _dictionaryini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'} # printing iniial_dictionaryprint("intial_dictionary", str(ini_dict)) # split dictionary into keys and valueskeys, values = zip(*ini_dict.items()) # printing keys and values separatelyprint ("keys : ", str(keys))print ("values : ", str(values)) |
Output:
intial_dictionary {'a': 'akshat', 'c': 'chandan', 'b': 'bhuvan'}
keys : ('a', 'c', 'b')
values : ('akshat', 'chandan', 'bhuvan')
Method #3: Using items()
# Python code to demonstrate# to split dictionary# into keys and values # initialising _dictionaryini_dict = {'a' : 'akshat', 'b' : 'bhuvan', 'c': 'chandan'} # printing iniial_dictionaryprint("intial_dictionary", str(ini_dict)) # split dictionary into keys and valueskeys = []values = []items = ini_dict.items()for item in items: keys.append(item[0]), values.append(item[1]) # printing keys and values separatelyprint ("keys : ", str(keys))print ("values : ", str(values)) |
Output:
intial_dictionary {'b': 'bhuvan', 'c': 'chandan', 'a': 'akshat'}
keys : ['b', 'c', 'a']
values : ['bhuvan', 'chandan', 'akshat']

