Let's learn how to work with python dictionary, dictionary is a collection object, here we see examples of how to create a python dictionary object, how python dictionary works, what are the built-in methods in dictionary object, and what type of data we can store in a dictionary object.
Dict = {'Course' : 'Python', 10: [14,4.5,.60], 'Provider' : 'WebTrainingRoom'}
Python Dictionary is a collection type object, which can store data using keay value “key:value” pair, in this article we will learn how to work with Python dictionary object.
We can create python dictionary object different ways, here are few examples.
class DictionaryExample(object):
def __init__(self):
self.Title = "Dictionary Examples";
def showFunction(obj):
Dict = {"Course:Python"}
print("New Dictionary created")
print(Dict)
We can create dictionary object with different type of keys, but we must make sure providing right key at the time of retrieval
Dict = {'Course' : 'Python', 10: [14,4.5,.60], 'Provider' : 'WebTrainingRoom'}
print(Dict)
We also can create dictionary with dict() method.
Dict = dict({1: 'Red', 2: 'Green', 3:'Blue'})
print(Dict)
Here are some python dictionary methods with examples.
clear()
Dict = dict({1: 'Red', 2: 'Green', 3:'Blue'})
Dict.clear();
print(Dict)
copy()
d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'})
d2=d1.copy();
print(d2)
keys()
d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'})
allkeys=d1.keys();
popitem() : Pick the last item from the dictionary
d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'})
d2=d1.popitem();
print(d2);
#result : (3, 'Blue')
pop()
d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'})
d2=d1.pop(2);
print(d2);
#result : ('Green')
update()
d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'})
d1.update({"color": "Orange"});
print(d1)
#result : {1: 'Red', 2: 'Green', 3:'Blue', "color": "Orange"}
values()
d1 = dict({1: 'Red', 2: 'Green', 3:'Blue'})
allValues=d1.values();
sort()
Dict = dict({"India": 'Delhi', "Uk": 'London', "USA":'Washington'})
lst1=list(Dict.keys());
lst1.sort();
for K in lst1:
print(":".join((K,str(Dict[K]))));
len()
Dict = dict({"India": 'Delhi', "Uk": 'London', "USA":'Washington'})
print("Length : %d" % len (Dict))
str()
Dict = dict({"India": 'Delhi', "Uk": 'London', "USA":'Washington'})
print(str(Dict))
After using dictionary object, we can finally delete the dictionary using "del" key word.
country = {
"name": "India",
"game": "Cricket",
"river": "Ganga"
}
del country
Python dictionary is just like generic list object that allow us to store values with key, we can add , remove any number of items, we can retrieve item by using key.