No description has been provided for this image

Open In Colab

Dictionaries in Python¶

1. Creating¶

In [ ]:
aDictExample={"name":"Peter",
             "speaks":['French', 'Spanish'],
             'country':'Morocco'}

# then
aDictExample

2. Accessing¶

Each dictionary element in Python can be accessed via keys NOT indexes (so no slices). Our aDictExample has these keys:

In [ ]:
aDictExample.keys()
In [ ]:
#then
aDictExample['speaks']
In [ ]:
# Here the index is for the list:
aDictExample['speaks'][0]

2. Replacing¶

In [ ]:
aDictExample['country']='Tunisia'
aDictExample

3. Deleting¶

In [ ]:
del aDictExample['country']

aDictExample

Becareful when using pop():

In [ ]:
aDictExample.pop('name')
In [ ]:
#now
aDictExample

4. Inserting¶

Let's create a dict from some lists:

In [ ]:
namesP=["Qing", "Françoise", "Raúl", "Bjork","Marie"]
agesP=[32,33,28,30,29]
countryP=["China", "Senegal", "España", "Norway","Korea"]
educationP=["Bach", "Bach", "Master", "PhD","PhD"]
In [ ]:
#notice alternative way of creating
classroom=dict(student=namesP,age=agesP,edu=educationP)
# see it:

classroom

There is no append to add an element, you need update:

In [ ]:
classroom.update({'country':countryP})
# now:
classroom