Python Dictionary
A dictionary is key-value pair in python.
The elements in dictionary is enclosed in flower brackets,
my_dict={"name":"srinidhi",
"rank":5,
"country":"India",
"fav_counties":["Japan","South Korea","London"]}
name, rank, country, fav_counties are keys.
The keys can be of any immutable data type.
The values can be of any data type.
To get the value of a certain key, use value() method.
my_dict.value(name)
"srinidhi"
Methods in dictionary
- items()
- keys()
- values()
- clear()
- get()
1. items() method is used to get all the elements in the dictionary.
my_dict.items()
(name:"srinidhi")
(rank:5)
(country:"India")
(fav_counties:["Japan","South Korea","London"])
Here the output will be tuples.
Get the separate key value pair by unpacking the tuples.
for key,value in my_dict:
print(key,"= ",value)
name= "srinidhi"
rank= 5
country= "India"
fav_counties:= ["Japan","South Korea","London"]
2. keys() method returns all the keys in the dictionary.
3. values() method returns all the values in the dictionary
4. get() returns none if key is absent in dictionary.
my_dict.get(age) does not throw error. it returns none.
5. clear() method is used to delete the entire elements in dictionary.
my_dict.clear()
print(my_dict)
{}
No comments:
Post a Comment