Show
The dictionary is an unordered collection that contains key:value pairs separated by commas inside curly brackets. Dictionaries are optimized to retrieve values when the key is known. The following declares a dictionary object. capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"} Above, capitals is a dictionary object which contains key-value pairs inside { }. The left side of : is a key, and the right side is a value. The key should be unique and an immutable object. A number, string or tuple can be used as key. Hence, the following dictionaries are also valid:
d = {} # empty dictionary numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value decNames={1.5:"One and Half", 2.5: "Two and Half", 3.5:"Three and Half"} # float key, string value items={("Parker","Reynolds","Camlin"):"pen", ("LG","Whirlpool","Samsung"): "Refrigerator"} # tuple key, string value romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int value However, a dictionary with a list as a key is not valid, as the list is mutable:
dict_obj = {["Mango","Banana"]:"Fruit", ["Blue", "Red"]:"Color"} But, a list can be used as a value.
dict_obj = {"Fruit":["Mango","Banana"], "Color":["Blue", "Red"]} The same key cannot appear more than once in a collection. If the key appears more than once, only the last will be retained. The value can be of any data type. One value can be assigned to more than one key.
>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"} >>> numNames {1:"One", 2:"Two", 3:"Three"} The dict is the class of all dictionaries, as shown below.
>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"} >>> type(numNames) <class 'dict'> A dictionary can also be created using the dict() constructor method.
>>> emptydict = dict() >>> emptydict {} >>> numdict = dict(I='one', II='two', III='three') >>> numdict {'I': 'one', 'II': 'two', 'III': 'three'} Access DictionaryDictionary is an unordered collection, so a value cannot be accessed using an index; instead, a key must be specified in the square brackets, as shown below.
>>> capitals = {"USA":"Washington DC", "France":"Paris", "India":"New Delhi"} >>>capitals["USA"] 'Washington DC' >>> capitals["France"] 'Paris' >>> capitals["usa"] # Error: Key is case-sensitive Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> capitals['usa'] KeyError: 'usa' >>> capitals["Japan"] # Error: key must exist Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> capitals['Japan'] KeyError: 'Japan'
Keys are case-sensitive. So, usa and USA are treated as different keys. If the specified key does not exist then it will raise an error. Use the get() method to retrieve the key's value even if keys are not known. It returns None if the key does not exist instead of raising an error.
>>> capitals = {"USA":"Washington DC", "France":"Paris", "Japan":"Tokyo", "India":"New Delhi"} >>> capitals.get("USA") 'Washington DC' >>> capitals.get("France") 'Paris' >>> capitals.get("usa") >>> capitals.get("Japan") >>> Access Dictionary using For LoopUse the for loop to iterate a dictionary in the Python script.
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New Delhi"} for key in capitals: print("Key = " + key + ", Value = " + capitals[key])
Key = 'USA', Value = 'Washington D.C.' Key = 'France', Value = 'Paris' Key = 'India', Value = 'New Delhi' Update DictionaryAs mentioned earlier, the key cannot appear more than once. Use the same key and assign a new value to it to update the dictionary object.
>>> captains = {"England":"Root", "Australia":"Smith", "India":"Dhoni"} >>> captains['India'] = 'Virat' >>> captains['Australia'] = 'Paine' >>> captains {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'} Use a new key and assign a value to it. The dictionary will show an additional key-value pair in it.
>>> captains['SouthAfrica']='Plessis' >>> captains {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'SouthAfrica': 'Plessis'} Deleting Values from a DictionaryUse the del keyword, pop(), or popitem() methods to delete a pair from a dictionary or the dictionary object itself. To delete a pair, use its key as a parameter. To delete a dictionary object, use its name.
>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'} >>> del captains['Srilanka'] # deletes a key-value pair >>> captains {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat'} >>> del captains # delete dict object >>> captains NameError: name 'captains' is not defined The NameError indicates that the dictionary object has been removed from memory. Retrieve Dictionary Keys and ValuesThe keys() and values() methods return a view objects containing keys and values respectively.
>>> d1 = {'name': 'Steve', 'age': 21, 'marks': 60, 'course': 'Computer Engg'} >>> d1.keys() dict_keys(['name', 'age', 'marks', 'course']) >>> d1.values() dict_values(['Steve', 21, 60, 'Computer Engg']) Check Dictionary KeysYou can check whether a paritular key exists in a dictionary collection or not usng the in or not in keywords, as shown below. Note that it only checks for keys not values.
>>> captains = {'England': 'Root', 'Australia': 'Paine', 'India': 'Virat', 'Srilanka': 'Jayasurya'} >>> 'England' in captains True >>> 'India' in captains True >>> 'France' in captains False >>> 'USA' not in captains True Multi-dimensional DictionaryLet's assume there are three dictionary objects, as below:
>>> d1={"name":"Steve","age":25, "marks":60} >>> d2={"name":"Anil","age":23, "marks":75} >>> d3={"name":"Asha", "age":20, "marks":70} Let us assign roll numbers to these students and create a multi-dimensional dictionary with roll number as key and the above dictionaries at their value.
>>> students={1:d1, 2:d2, 3:d3} >>> students {1: {'name': 'Steve', 'age': 25, 'marks': 60}, 2: {'name': 'Anil', 'age': 23, 'marks': 75}, 3: {'name': 'Asha', 'age': 20, 'marks': 70}}< The student object is a two-dimensional dictionary. Here d1, d2, and d3 are assigned as values to keys 1, 2, and 3, respectively. The students[1] returns d1.
>>> students[1] {'name': 'Steve', 'age': 25, 'marks': 60} >>> students[1]['age'] 25 Built-in Dictionary Methods
Python Questions & Answers
|