DICTIONARIES



Python - Dictionaries


A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values.


Create and print a dictionary:


dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
print(dict)

{'brand': 'apple', 'model': '10s', 'year': 2019}


Accessing Items :


We can access the items of a dictionary by referring to its key name, inside square brackets.There is also a method called get() that will give you the same result.


1.USING 'keyname':

dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
x=dict["brand"]
print(x)

apple

2.USING get():

dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
x=dict.get("model")
print(x)
 10s

Change Values :


We can change the value of a specific item by referring to its key name.


dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
dict["year"]=2018
{'brand': 'apple', 'model': '10s', 'year': 2018}


Loop Through a Dictionary :


We can loop through a dictionary by using a for loop.When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.


Print all key names in the dictionary, one by one :

dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
for i in dict:
 print (i)

brand
model
year

Print all values in the dictionary, one by one :

dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
for i in dict:
 print (dict[i])

apple
10s
2019

You can also use the values() function to return values of a dictionary :

dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
for i in dict.values():
 print (i)

apple
10s
2019

Loop through both keys and values, by using the items() function :

dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
for i,i2 in dict.items():
 print (i,i2)

brand apple
model 10s
year 2019


Check if Key Exists :


To determine if a specified key is present in a dictionary use the 'in' keyword.


Check if "model" is present in the dictionary :


dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
if "model" in dict:
    print("yes,'model' is one of the keys in dict")

yes,'model' is one of the keys in dict



Dictionary Length :


To determine how many items (key-value pairs) a dictionary has,we have to use the len() method.


dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
print(len(dict))

3

Adding Items :


Adding an item to the dictionary is done by using a new index key and assigning a value to it.


dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
dict["color"]="red"
print(dict)

{'brand': 'apple', 'model': '10s', 'year': 2019, 'color': 'red'}


Removing Items :


There are several methods to remove items from a dictionary.They are:
pop( ), popitem( ), del , clear( ).


The pop() method removes the item with the specified key name ;


dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
dict.pop("model")
print(dict)

{'brand': 'apple', 'year': 2019}


The popitem( ) method removes the last inserted item (in versions before 3.7, a random item is removed instead):


dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
dict.popitem()
print(dict)

{'brand': 'apple','model': '10s'}


The del keyword removes the item with the specified key , and can also delete the dictionary completely.


dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
del dict["model"]
print(dict)

{'brand': 'apple', 'year': 2019}


NOW,using del without keyword

dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
del dict
print(dict)

##it gets an error as dict gets deleted

The clear() keyword empties the dictionary:


dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
dict.clear()
print (dict)

{}




Copy a Dictionary :


You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary method copy().


dict={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
dict1=dict.copy()
print(dict1)

{'brand': 'apple', 'model': '10s', 'year': 2019}


Another way to make a copy is to use the built-in method dict().


dict1={
    "brand":"apple",
    "model":"10s",
    "year" : 2019
    }
dict2=dict(dict1)
print(dict2)

{'brand': 'apple', 'model': '10s', 'year': 2019}


Nested Dictionaries :


A dictionary can also contain many dictionaries, this is called nested dictionaries.


myfamily = {
    "parent1":{
        "name":"jayy",
        "age":45
        },
    "parent2" :{
        "name":"sweejya",
        "age":35
        },
    "child1":{
        "name":"sanvi",
        "age":21
        },
    "child2":{
        "name":"suhansh",
        "age":19
        },
    "child3":{
        "name":"pranjal",
        "age":18
        }
    }
print(myfamily)

==== O/P ======
{'parent1': {'name': 'jayy', 'age': 45}, 'parent2': {'name': 'sweejya', 'age': 35}, 'child1': {'name': 'sanvi', 'age': 21}, 'child2': {'name': 'suhansh', 'age': 19}, 'child3': {'name': 'pranjal', 'age': 18}}


If you want to nest three dictionaries that already exists as dictionaries


child1={
        "name":"sanvi",
        "age":21
        }
child2={
        "name":"suhansh",
        "age":19
        }
child3={
        "name":"pranjal",
        "age":18
}
myfamily={
    "child1" : child1,
    "child2" : child2,
    "child3" : child3
    }
print(myfamily)

======= O/P =========
{'child1': {'name': 'sanvi', 'age': 21}, 'child2': {'name': 'suhansh', 'age': 19}, 'child3': {'name': 'pranjal', 'age': 18}}


The dict() Constructor :


It is also possible to use the dict() constructor to make a new dictionary.


dict1=dict(brand="apple",model="10s",year=1964)
print(dict1)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment

=====O/P====
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Dictionary Methods


MethodDescription
clear()Removes all the elements from the dictionary
copy()Returns a copy of the dictionary
fromkeys()Returns a dictionary with the specified keys and values
get()Returns the value of the specified key
items()Returns a list containing the a tuple for each key value pair
keys()Returns a list containing the dictionary's keys
pop()Removes the element with the specified key
popitem()Removes the last inserted key-value pair
setdefault()Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update()Updates the dictionary with the specified key-value pairs
values()Returns a list of all the values in the dictionary


RegEx SETS

Python - RegEx SETS

posted on 2019-11-12 23:06:24 - Python Tutorials


RegEx_Functions

Python - RegEx_Functions

posted on 2019-11-09 06:07:29 - Python Tutorials


RegEx_Sets

Python - RegEx_Sets

posted on 2019-11-09 05:30:54 - Python Tutorials


Prompt Examples

ChatGPT Prompt Examples

posted on 2023-06-21 22:37:19 - ChatGPT Tutorials


Use Cases

Chat GPT Key Use Cases

posted on 2023-06-21 21:03:17 - ChatGPT Tutorials


Prompt Frameworks

Prompt Frameworks

posted on 2023-06-21 19:33:06 - ChatGPT Tutorials