dictionary Flashcards
(90 cards)
d = {100:’durga’, 101:’ravi’, 102:’sagar’, 103:’chetan’}
d.setdefault(100,”Suhail”)
d
d.setdefault(200,”Ishita”)
d
d.setdefault(500)
d
> > > d.setdefault(100,”Suhail”)
‘durga’
d
{100:’durga’, 101:’ravi’, 102:’sagar’, 103:’chetan’}
d.setdefault(200,”Ishita”)
‘Ishita’
d
{100: ‘durga’, 101: ‘ravi’, 102: ‘sagar’, 103: ‘chetan’, 200: ‘Ishita’}
d.setdefault(500)
d
{100: ‘durga’, 101: ‘ravi’, 102: ‘sagar’, 103: ‘chetan’, 200: ‘Ishita’, 500: None}
Syntax of update()
dictionary.update(iterable)
iterable: A dictionary
Slicing is allowed in dictionary?
No
How to get items of dict using for loop
For k,v in d.items():
print(k,v)
If the specified value in pop() of dict and also default value is not given then
KeyError
Datatype of values of dictionary
Any data type
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.pop(“model”)
print(x)
Mustang
Return type of popitem()
tuple
How to get values of dict using for loop
For v in d.values():
print(v)
In dictionary, are duplicates allowed
For keys duplicates are not allowed
For values duplicates are allowed
How we can remove all entries from the dict but after deleting the elements still we can access dict
d.clear()
How do you create empty dictionary?
d = { }
Or
d = dict()
Take table
__________________
100 | ‘Krishna’
__________________
200 | ‘Ravi’
__________________
300 | ‘Shiva’
__________________
Write code for this table in python
d = {100: ‘Krishna’, 200: ‘Ravi’, 300: ‘Shiva’}
d = {100:’durga’, 200:’ravi’, 300:’shiva’}
print(del d[100])
print(d)
print(del d[400])
print(d)
SyntaxError: invalid syntax
print(del d[100])
^^^
Dictionaries are mutable or immutable
Mutable
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.get(“hi”)
print(x)
None
get()
- Return the value associated with the key
- It doesn’t gives error
Dict
How to removes the item that was last inserted into the dictionary.
popitem() method
Syntax of d.pop()
dictionary.pop(keyname, defaultvalue)
keyname: Required. The keyname of the item you want to remove
defaultvalue: Optional. A value to return if the specified key do not exist.
If this parameter is not specified, and the no item with the specified key is found, an error is raised
Syntax of get()
dictionary.get(keyname, value)
keyname: Required. The keyname of the item you want to return the value from
value: Optional. A value to return if the specified key does not exist. Default value None
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
x = car.get(“price”, 15000)
print(x)
15000
How to get keys in python using for loop of dict
d = {100:’durga’, 200:’ravi’, 300:’shiva’}
for k in d.keys():
print(k)
100
200
300
How to get each key value pair of dict
items()
data types of items of dictionary
Dictionary items contain 2 things
key values
Data type of Keys: Immutable: int, str, tuples, booleans, None,
frozenset
List, dictionaries, set can’t be used as keys as they are mutable
Data type of values: Any data type