Sunday, October 27, 2019

Python Dictionary

Dictionaries are another example of a data structure. A dictionary is used to map or associate things you want to store the keys you need to get them. A dictionary in Python is just like a dictionary in the real world. Python Dictionary are defined into two elements Keys and Values.

Keys will be a single element
Values can be a list or list within a list, numbers, etc.

Below is how to declare a dictionary in Py

Dict = { ' Tim': 18,  xyz,.. }

Properties of Dictionary Keys

There are two important points while using dictionary keys

More than one entry per key is not allowed ( no duplicate key is allowed)
The values in the dictionary can be of any type while the keys must be immutable like numbers, tuples or strings.
Dictionary keys are case sensitive- Same key name but with the different case are treated as different keys in Python dictionaries.

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
print((Dict['Tiffany']))

Copying dictionary
You can also copy the entire dictionary to new dictionary. For example, here we have copied our original dictionary to new dictionary name "Boys" and "Girls".

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
studentX=Boys.copy()
studentY=Girls.copy()
print(studentX)
print(studentY)


Updating Dictionary
You can also update a dictionary by adding a new entry or a key-value pair to an existing entry or by deleting an existing entry. Here in the example we will add another name "Sarah" to our existing dictionary.

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Dict.update({"Sarah":9})
print(Dict)

Delete Keys from the dictionary
Python dictionary gives you the liberty to delete any element from the dictionary list. Suppose you don't want the name Charlie in the list, so you can delete the key element by following code.

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
del Dict ['Charlie']
print(Dict)

Getting items from dict

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
print("Students Name: %s" % list(Dict.items()))

We use the code items() method for our Dict.
When code was executed, it returns a list of items ( keys and values) from the dictionary

Check if a given key already exists in a dictionary

For a given list, you can also check whether our child dictionary exists in a main dictionary or not. Here we have two sub-dictionaries "Boys" and "Girls", now we want to check whether our dictionary Boys exist in our main "Dict" or not. For that, we use the forloop method with else if method.

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
for key in list(Dict.keys()):
    if key in list(Boys.keys()):
        print(True)
    else:     
        print(False)

Sorting the Dictionary
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
Students = list(Dict.keys())
Students.sort()
for S in Students:
      print(":".join((S,str(Dict[S]))))

We declared the variable students for our dictionary "Dict."
Then we use the code Students.sort, which will sort the element inside our dictionary
But to sort each element in dictionary, we run the forloop by declaring variable S
Now, when we execute the code the forloop will call each element from the dictionary, and it will print the string and value in an order

Below are the operations allowed on Dict

copy() Copy the entire dictionary to new dictionary dict.copy()
update() Update a dictionary by adding a new entry or a key-value pair to an
existing entry or by deleting an existing entry. Dict.update([other])
items() Returns a list of tuple pairs (Keys, Value) in the dictionary. dictionary.items()
sort() You can sort the elements dictionary.sort()
len() Gives the number of pairs in the dictionary. len(dict)
cmp() Compare values and keys of two dictionaries cmp(dict1, dict2)
Str() Make a dictionary into a printable string format Str(dict)

References:
https://www.guru99.com/python-dictionary-beginners-tutorial.html

3 comments: