Dictionary in Python

Dictionary in Python

In Python, a dictionary is a collection that is ordered( in versions 3.5 or Later ),  changeable and indexed, dictionaries are written with curly brackets, and they have keys and values.   


dict1 = {"python":"programming language", "akash":{"class":12, "roll_no":15}, 21:12}
print(dict1["akash"]["class"])

dict2 = dict1.copy()                                  #if we apply any changes to d2 then d1 doesn't change
dict2.update({"aka":"macskill"})
print(dict1,"\n", dict2)                         # as you can see when we add to d2 then d1 remain same

dict1["Be Kind"] = 'Yes'                          #add item in dictionary
print(dict1)

print(dict1.get('py'))                     # if that key is not in dict, so get() not give error its just say None.
print(dict1.get('python', "Not Found"))         # if that key is not present,its simply say Not Found or                                                                                whatever you write
print(dict1.get('aksh', "Not Found"))

print(dict1.keys())                        # keys() used to print keys present in dictionary
print(dict1.values())                    # value() used to print value present in dictionary
print(dict1.items())                      # items() used to print key:value pairs present in dictionary

dict1.clear()
py = print(dict1.pop("python"))               # it will pop a specific item in dictionary
print(dict1.popitem())                             # it will pop last element of dictionary


''' Merging two List into a Dictionary'''
keys = ['Akash', 'Tony', 'Thor', 'Oliver']
values = ['Python', 'Jarvis', 'Hammer', 'Game Development']
data = dict(zip(keys, values))
print(data)


''' Program : User Input Dictionary '''
apnidict = {"Mutable": "Changeable", "Immutable":"Cannot Change "}
inp = input("Enter the word to know its meaning : ")
a= inp.capitalize()
print("Meaning of ", inp, "is ->", apnidict[a])
print(" Thanks :) for choosing \vapnidict ")



''' Program : Ratings of Movie'''
bestmovie = [ ]
movierating = {"Endgame": 9.8, "Avengers": 8.2, "Infinity War": 6, "Intestellar": 4.5}
for movie in movierating :
    if movierating[movie] >= 8:
        bestmovie.append(movie)
print(bestmovie)
#OR we can also do upper Program by LIST Comprehension :
print([film for film in movierating if movierating[film] >= 6 ])


Disqus Comments