Computer >> Computer tutorials >  >> Programming >> Python

How to convert Python Dictionary to a list?


Python's dictionary class has three methods for this purpose. The methods items(), keys() and values() return view objects comprising of tuple of key-value pairs, keys only and values only respectively. The in-built list method converts these view objects in list objects.

>>> d1 = {'name': 'Ravi', 'age': 23, 'marks': 56}
>>> d1.items()
dict_items([('name', 'Ravi'), ('age', 23), ('marks', 56)])
>>> l1 = list(d1.items())
>>> l1
[('name', 'Ravi'), ('age', 23), ('marks', 56)]
>>> d1.keys()
dict_keys(['name', 'age', 'marks'])
>>> l2 = list(d1.keys())
>>> l2
['name', 'age', 'marks']
>>> l3 = list(d1.values())
>>> l3
['Ravi', 23, 56]