Understanding the Python vocabulary

Python Methods and Functions

Let's look at an example, let's assume we have two lists with the names of keys and values ​​now,

# Python code to demonstrate the dictionary
# understanding

 
# Lists to represent keys and values ​​

keys = [ 'a' , ' b' , 'c' , 'd' , ' e' ]

values ​​ = [ 1 , 2 , 3 , 4 , 5

 
# but this line shows word comprehension

myDict = {k : v for (k, v) in zip (keys, values)} 

 
# We can use below too
# myDict = dict (zip (keys, values))

 

print (myDict )

Output:

 {'a': 1,' b': 2, 'c': 3,' d': 4, 'e': 5} 

We can also make a dictionary from a list using comprehension

Output:

 {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} 

and how,

# Python code to showcase the dictionary
# generated using a list comprehension

myDict = {x: x * * 2 for x in [ 1 , 2 , 3 , 4 , 5 ]}

print (myDict)

sDict = {x.upper (): x * 3 for x in 'coding' }

print (sDict)

Output:

 {'O':' ooo', 'N':' nnn', 'I':' iii', 'C':' ccc', 'D':' ddd', 'G':' ggg'} 

We can use dictionary expressions with if and else statements, as well as with other expressions. This example below maps numbers to their cubes that are not divisible by 4:

# Python code to showcase the dictionary
# understanding using if.

newdict = {x: x * * 3 for x in range ( 10 ) if x * * 3 % 4 = = 0 }

print (newdict)

Output:

 {0: 0, 8: 512, 2: 8, 4: 64, 6: 216} 

This article courtesy of Shantanu Sharma. If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or email the article [email protected] See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you'd like to share more information on the topic discussed above.





Tutorials