dict becomes list instance method in python

  • 2021-07-01 07:55:59
  • OfStack

How does dict (dictionary) become list (list) in python?

Note: List cannot be converted to dictionary

1. The converted list is an unordered list


a = {'a' : 1, 'b': 2, 'c' : 3}

 

# In a dictionary key Convert to list 

key_value = list(a.keys())

print(' In a dictionary key Convert to list: ', key_value)

 

# In a dictionary value Convert to list 

value_list = list(a.values())

print(' In a dictionary value Convert to list: ', value_list)

Run results:


 In a dictionary key Convert to list: ['a','b','c']

 In a dictionary value Convert to list: [1,2,3]

2. The converted list is an ordered list


import collections

z = collections.OrderedDict()

z['b'] = 2

z['a'] = 1

z['c'] = 3

z['r'] = 5

z['j'] = 4

 

# In a dictionary key Convert to list 

key_value = list(z.keys())

print(' In a dictionary key Convert to list: ', key_value)

 

# In a dictionary value Convert to list 

value_list = list(z.values())

print(' In a dictionary value Convert to list: ', value_list)

Run results:


 In a dictionary key Convert to list: ['b','a','c','p','j']

 In a dictionary value Convert to list: [2,1,3,5,4]

Note: The version of Python used here is 3. x.

Python dict and list Conversion

There is an dict here


d1 = {
 'en':' English ',
 'cn':' Chinese ',
 'fr':' French ',
 'jp':' Japanese '
}

values and keys can be extracted using d1.keys () or d1.values (). You can also generate keys, and values with the following code:


list_values = [i for i in d1.values()]
list_keys= [ i for i in d1.keys()]

Thus, list_keys is: ['en', 'cn', 'fr', 'jp'] list_values is: ['English', 'Chinese', 'French', 'Japanese']

To combine these two list into one dict, you can combine the zip () function.


d2=dict(zip(list_keys,list_values))
print('d2',d2)

The result is:


d2 {'en': ' English ', 'cn': ' Chinese ', 'fr': ' French ', 'jp': ' Japanese '}

The above is all the knowledge points about how dict became list in python. If you want to learn more about python, you can refer to Python column. Thank you for your support to this site.


Related articles: