[go: up one dir, main page]

0% found this document useful (0 votes)
7 views8 pages

Dictionary

Dictionaries in Python are unordered collections of key-value pairs, where each key is unique and can be of any data type. They can be created using curly braces or the dict() function, and allow for the storage of various data types including lists and tuples. Accessing values is done through keys rather than index positions, and dictionaries are mutable, allowing for the addition, modification, and deletion of key-value pairs.

Uploaded by

compnetworxxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views8 pages

Dictionary

Dictionaries in Python are unordered collections of key-value pairs, where each key is unique and can be of any data type. They can be created using curly braces or the dict() function, and allow for the storage of various data types including lists and tuples. Accessing values is done through keys rather than index positions, and dictionaries are mutable, allowing for the addition, modification, and deletion of key-value pairs.

Uploaded by

compnetworxxx
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Dictionary Python data structure

# Q - what are dictionaries?


# A - unordered collections of data in key: value pair.
Intro to dictionaries:
in JavaScript its json object and in python its dictionary
Mapping Data Type (dict): Dictionaries are mappings and do not retain
order!(Unordered)
To understand the Dictionary you have to realize the real dictionary in a
dictionary there is a word and there is a meaning organized with alphabetic
manner same follows you want to go with the a you get the a then the
meaning that’s how it work same follow with python dictionary as well it
has
Collection type - having Key Value pair
Word: meaning
Dictionary work with keys values pairs
Remember dict is like something a map or something in association with
two values Keys and Values and every keys is unique
In a list, index value is an integer, while in a dictionary index value can be
any other data type and are called keys.
List and Tuple are mainly dependant on sequence so we have zero index
and we some value we have one index we have some value whereas in
dictionary there is no zero one to three index we have keys and value pair
how to create dictionaries ?
to create a dictionary create a variable name for a dict and using an
assignment operator Followed by curly brackets or Curly braces
next line then we have to provide the keys and values
then we use colon in between to separate them and to add another key
value pair we separate it by Commas so each pair separate by comma
dictionary process key value just like Hash Table
Example
user = {'name' : 'Harshit', 'age' : 24}
here name is a key followed by colon then Harshit is the value)
#name key hae Harshit value key value pair
Harshit yaha name ko humne string tara create kiya hae keys ko bhi
now we want to print this up I can get key value pair again
# print(user)
# print(type(user))

Another Example
class_room{"name":"Shahid","age":43}
# dict declration in a var called class_room
# having two key and value pairs
# one is name in which value is Shahid
# second is age in which value is 43

Imp! Second method to create dictionary using dict func


dict method
user1 = dict(name = 'Harshit', age = 24)
#yaha pe keys pe quotes aur laganae ki zarorrat nahi hae
# print(user1)
print(type(user1))

#Note sometime when you print out the dict it will be different orders

Another way of defining dictionary by using for loop in the dict


# key x and value is x+1
#followed by for loop stmt
my_dictionary ={x:x +1 for x in range(10) }
print(my_dictionary )
Associate with any Data type:
we can store different type of data type in a dictionary also based upon
program task
emp ={"name":"Shubham","age":35,"smoke":False,("h","w"):(6,75)}
#diff data type so here we have
#string,int,boolean value,tuple

Grabbing data from the dictionary


# How to access data from dictionary
# NOTE - you can’t access the dictionary element based on it’s position
value.There is no indexing because of unordered collections of data.
koi index bolkar nahi hoti key ki ,madad se acces karenge
class_room{"name":"Shahid","age":43}
here in this example name is covering it index with position in form of
name and shahid here is the value
if it talk about a simple list
a=[20,30,40] # here 0 is the index position having a value of 20
Similarly for dictionary so dictionary is depend on pairs and it’s really
important when your are transferring a Data you have a key value which
you define yourselves so you give it a name or in toe what content ia
sending
So if I a storing a name I can gave a name took my key that it a name
If I am storing age then I give name to my key that its a age
Now the second thing is indexing is different
During my list I have to give index position but in dict instead of using
indexes we use the actual key so I have to give a key name to get a value
by opening square brackets with the name of a key
print(a[0])#list
print (class_room["name"])#key name
it will give value which is associated with this key
and also there is no sequence for the value we are storing so if have to
access age I will not able to access with index position I have to pass age as
my key to get a value 22
print (class_room["age"])

we have two fuction if we want to separately display keys and values


print(class_room.keys())#access only keys
print(class_room.items())#access only values

Create a variable name user and create dict


user{"name":"Shahid","age":43}
Example:
# print(user['name'])
# print(user['age'])
# which type of data a dictionary can store ?
# anything
# numbers, strings, list , dictionary
Example
user_info = {
'name' : 'harshit',
'age' : 24,
("h","w"):(6,75),#tuple
'fav_movies' : ['coco', 'kimi no na wa'],#dictionary ke andar list
'fav_tunes' : ['awakening', 'fairy tale'],
}
# print(user_info['fav_movies'])
Why we use dictionaries?
Because of limitations of lists , lists are not enough to represent real data
but in dict you can insert list inside dictionary Insert tuple inside dict
nested dictionary
#dictionary ke andar dictionary
users ={
user1 :{ 'name' : 'harshit',
'age' : 24,
'fav_movies' : ['coco', 'kimi no na wa'] ,
'fav_tunes' : ['awakening', 'fairy tale'],
}
}

Access complete data I have to pass key


If I need to access tuple from this dict
print(emp[("h","w")])

if I try to access something which is not available


print(emp["salary"])
# throw key error

Need to be clarified
#exception handling
try:#error handling
print(my_dictionary [1])

except Exception as e:
print(Exception)

#result 1
Or if I pass index value
Adding more values in a dict a we can’t able to do that in tuple which is
immutable in nature
Mutability:
List is mutable so we can easily add similarly like list dict is also mutable
Take your variable dict open and closing square brackets all you have to
pass name of key and a value associate with this key to add new element in
the dict
Adding New Elements in the Dict
emp["salary"]=10000
print(emp["salary"])
print(emp)#salary added to the last value

# changing the value of a existing key


# changing the value of a Existing key
user1["name"] = "Vashit"
print(user1)

# Delete the specify key


Using the del keyword followed by the name of target dict and the name
of a key which is to be delete
del user1['name']
print(user1)

Note :change of one object is also applied to other one if you don’t
want this happened create dcopy of the object

# List Example
user = ['Harshit', 24, ['coco', 'kimi no na wa'], ['awakening', 'fairy tale']]
# this list contains user name , age ,
Nested list me index me user ki fav movies ki list , fav tunes
# you can do this but this is not a good way to do this.
user_info = {
'name' : 'harshit',
'age' : 24,
("h","w"):(6,75),#tuple
'fav_movies' : ['coco', 'kimi no na wa'],#dictionary ke andar list
'fav_tunes' : ['awakening', 'fairy tale'],
}
print(user_info)

# How to add data to empty dictionary


user_info2 = {}#empty dictionary
user_info2['name'] = 'mohit'#keys aur values ko defined kar dijye
user_info2['age'] = 19
print(user_info2)

# check if key exist in dictionary name or age


# if 'name' in user_info:#key name and dictionary name here in keyword
will check keyword for key in dictionary
# print('present')
# else:
# print('not present')
# check if value exist in dictionary ----> values method
# if 24 in user_info.values():#to check particular values using .value
method keyword in will not chk for keys and its specific for data type
# print('present')
# else:
# print('not present')

# if 'name' in d:
# print('present')
# else:
# print('not present')

# if d.get('names'):
# print('present')
# else:
# print('not present')

# if None ----> False, else -----> True

# loops in dictionaries # how to run loops


# for i in user_info:#all the values will print
# print(user_info[i])
Looping and In Keyword in dictionary
# in keyword and iterations(looping) in dictionary

# Shallow Copies with Dictionary


# shallow copy is the two copies of a data structure share the same set of a
element

my_dict= my_dict1# just copying since both share the


same set as element in memory so they are going to any
changes that occur to any one both will effect at a same
time
to prevent this we use deep copying
we can use dictionary to dealt with http clients and many thing

You might also like