Python dictionary Function

Python dictionary is similar to the dictionary variable type of C#, or hash (associative) array of other languages. Python dictionary can store different variable types.

dictionary initialization:

>>> x = {"USA":3,"India":11,"Brazil":1}
>>> x
{'Brazil':1,'India':11,'USA':3}
>>> x = {2:3,"India":11,"Brazil":[1,2,3]}
>>> x
{2: 3, 'Brazil': [1,2,3],'India': 11}
Add items to dictionary:
>>> x[12] = "aa"
>>> x
{2: 3, 12: 'aa', 'Brazil': [1,2,3],'India': 11}
Delete items of dictionary:
>>> del x[2]
>>> x
{12: 'aa', 'Brazil': [1,2,3],'India': 11}
>>> x.clear() #remove all entries in x
>>> del x delete x

Update dictionary item value:
>>> x = {12: 'aa', 'Brazil': [1,2,3],'India': 11}
>>> x[12] = "bb" #update x[12] value
>>> x
{12: 'bb', 'Brazil': [1,2,3], 'Inida': 11}
Loop through dictionary:
>>> x = {"USA":3,"India":11,"Brazil":1}
>>> for i in x:
>>> print(i,x[i])
Brazil 1
USA 3
India 11












endmemo.com © 2024  | Terms of Use | Privacy | Home