Python tutorial- Dictionary


A dictionary or a hash table stores pairs of values and keys. You can access an item of a dictionary through its key.
>>> Dic={'1':'Cambodia','2':'China','3':'USA'}
>>> Dic['1']

You also can create a dictionary from a sequence of pair items or from other dictionaries by using dict() method.
>>> lst=[(1,'Pizza'),(2,'Cheese'),(3,'Fried Chicken')]
>>> Dic1=dict(lst)
>>> Dic1[1]

Dictionary: get, items, keys, values, pop, update, and clear methods:
To access the value of an item of a dictionary, you can use get() method:
>>> Dic1.get(1)
>>> Dic1.get(4)
The items() method can return all items of the dictionary in the form (key,value):
>>> Dic1.items()
[(1, 'Pizza'), (2, 'Cheese'), (3, 'Fried Chicken')]
To access all keys contained in a dictionary, use keys() method, and to access all values, use values() method:
>>> Dic1.keys()
[1, 2, 3]
>>> Dic1.values()
['Pizza', 'Cheese', 'Fried Chicken']
You can remove all items of a dictionary by using clear() method:
Like the case of sequence, you can use pop() method to remove an item from a dictionary. However, the pop() method of a dictionary is naturally created to remove an item at whatever position, not just the last one.
>>> Dic1.pop(1)
>>> Dic1
{2: 'Cheese', 3: 'Fried Chicken'}

You can also update a value of item of a dictionary by using update method:
>>> x={1:'Pizza'}
>>> Dic1.update(x)
>>> Dic1
{1: 'Pizza', 2: 'Cheese', 3: 'Fried Chicken'}
>>> y={2:'Hamburger'}
>>> Dic1.update(y)
>>> Dic1
{1: 'Pizza', 2: 'Hamburger', 3: 'Fried Chicken'}
To remove all items of the dictionary, you can use clear() method:
>>> Dic1.clear()
>>> Dic1

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.