The dictionary method popitem does not raise an exception if it is called on an empty dictionary.

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 Dictionary

Dictionary 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 Loop

Use 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 Dictionary

As 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 Dictionary

Use 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 Values

The 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 Keys

You 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 Dictionary

Let'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

Method Description
dict.clear() Removes all the key-value pairs from the dictionary.
dict.copy() Returns a shallow copy of the dictionary.
dict.fromkeys() Creates a new dictionary from the given iterable (string, list, set, tuple) as keys and with the specified value.
dict.get() Returns the value of the specified key.
dict.items() Returns a dictionary view object that provides a dynamic view of dictionary elements as a list of key-value pairs. This view object changes when the dictionary changes.
dict.keys() Returns a dictionary view object that contains the list of keys of the dictionary.
dict.pop() Removes the key and return its value. If a key does not exist in the dictionary, then returns the default value if specified, else throws a KeyError.
dict.popitem() Removes and return a tuple of (key, value) pair from the dictionary. Pairs are returned in Last In First Out (LIFO) order.
dict.setdefault() Returns the value of the specified key in the dictionary. If the key not found, then it adds the key with the specified defaultvalue. If the defaultvalue is not specified then it set None value.
dict.update() Updates the dictionary with the key-value pairs from another dictionary or another iterable such as tuple having key-value pairs.
dict.values() Returns the dictionary view object that provides a dynamic view of all the values in the dictionary. This view object changes when the dictionary changes.

Which dictionary method returns the value associated with a specified key if the key is not found it returns a default value?

Python Dictionary get() Method Syntax: key: The key name of the item you want to return the value from. Value: (Optional) Value to be returned if the key is not found. The default value is None.

Which of the following methods removes all of the key value pairs from a dictionary called D?

The popitem method returns a randomly selected key-value pair, as a tuple, and removes that key-value pair from the dictionary.

Which method returns all of dictionary's keys as dictionary view?

Python Dictionary keys() Method The keys() method returns a view object. The view object contains the keys of the dictionary, as a list. The view object will reflect any changes done to the dictionary, see example below.

Which method would you use to returns all the elements in a dictionary as a list of key

In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Parameters: This method takes no parameters. Returns: A view object that displays a list of a given dictionary's (key, value) tuple pair.

Toplist

Neuester Beitrag

Stichworte