DEV Community

Cover image for {"Dictionary" : "fun"}
Umme Abira Azmary
Umme Abira Azmary

Posted on

{"Dictionary" : "fun"}

A dictionary is an unordered collection that consists of ​key-value​ pairs. Dictionaries are bounded by curly braces and have a list of ​key: value ​pairs which are separated by comma (,)

dict1 = {}
dict1['name'] ='mouly'
dict1['address'] = 'bogura'
dict1['profession'] = 'student'
print(dict1)
Enter fullscreen mode Exit fullscreen mode

Output:

{'name': 'mouly', 'address': 'bogura', 'profession': 'student'}
Enter fullscreen mode Exit fullscreen mode

Here, name, address, profession are keys. ​Keys​ need to be immutable type and keys are case sensitive.

Empty Dictionary

dict2 = {}
print(dict2)
Enter fullscreen mode Exit fullscreen mode

Output:

{}
Enter fullscreen mode Exit fullscreen mode

Accessing a dictionary inside a dictionary

m_zen = { 88017:'rihan', 88015:'kiran', 88018 : ['sonam','riki'], 88013: 'harmeonie', 88016 :{24: 'chinal',26:'sonu'}}
y = m_zen[88016][26]
print(y)
Enter fullscreen mode Exit fullscreen mode

Output:

sonu
Enter fullscreen mode Exit fullscreen mode

Adding two list as key,value in dictionary

For this, we have to use zip function.

name = ['darla','remina','sonam','kiran']
age = [23, 45, 3, 44]
res = dict(zip(name,age))
print(res)
Enter fullscreen mode Exit fullscreen mode

Output:

{'darla': 23, 'remina': 45, 'sonam': 3, 'kiran': 44}
Enter fullscreen mode Exit fullscreen mode

Length of a dictionary

store = {'bangla' : 3, 'english' : 4, 'german' : 5, 'arabic' : 2}
print(len(store))
Enter fullscreen mode Exit fullscreen mode

Output:

4
Enter fullscreen mode Exit fullscreen mode

Dictionaries are mutable

Dictionaries are mutable while keys are immutable. So we can change the values of a dictionary.

dict3 = {'nila': 2345, 'mili': 2356, 'mona': 3456}
y = dict3['mona']
print(y)
Enter fullscreen mode Exit fullscreen mode

Output:

3456
Enter fullscreen mode Exit fullscreen mode

This is how we can access the value of a specific key of a dictionary.

We can also get the same value by using get function. The benefit of using get function is that, it does not give an error if we can not find value of a key; rather it gives None as output.

dict4 = {'nila': 2345, 'mili': 2356, 'mona': 3456}
y = dict4.get('nila')
print(y)
Enter fullscreen mode Exit fullscreen mode

Output:

2345
Enter fullscreen mode Exit fullscreen mode
dict4 = {'nila': 2345, 'mili': 2356, 'mona': 3456}
#x = dict4['rita']                                     #if we print it, it will give a KeyError
y = dict4.get('rita')
print(y)
Enter fullscreen mode Exit fullscreen mode

Output:

None
Enter fullscreen mode Exit fullscreen mode

changing the value of a dictionary

dictt = {'saturn': 2, 'moon': 1, 'mars': 'red'}
print(dictt)
dictt['moon'] = 'earth'
print(dictt)
Enter fullscreen mode Exit fullscreen mode

Output:

{'saturn': 2, 'moon': 1, 'mars': 'red'}
{'saturn': 2, 'moon': 'earth', 'mars': 'red'}
Enter fullscreen mode Exit fullscreen mode
address = {'room':3,'home':4,'street':2}
print(address)
address['room']= address['room']+ 2
print(address)
Enter fullscreen mode Exit fullscreen mode

Output:

{'room': 3, 'home': 4, 'street': 2}
{'room': 5, 'home': 4, 'street': 2}
Enter fullscreen mode Exit fullscreen mode

Here we can see how we the change value of a key of a dictionary.

Looping through a dictionary

songs = { 'red':'All Too Well', 1989: 'Style', 'reputation' : 'Gorgeous'}
for i in songs.keys():
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output:

red
1989
reputation
Enter fullscreen mode Exit fullscreen mode
songs = { 'red':'All Too Well', 1989: 'Style', 'reputation' : 'Gorgeous'}
for i in songs.values():
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output:

All Too Well
Style
Gorgeous
Enter fullscreen mode Exit fullscreen mode
songs = { 'red':'All Too Well', 1989: 'Style', 'reputation' : 'Gorgeous'}
for i,j in songs.items():
    print(i, j)
Enter fullscreen mode Exit fullscreen mode

Output:

red All Too Well
1989 Style
reputation Gorgeous
Enter fullscreen mode Exit fullscreen mode

If I update a dictionary, then the updated list of keys will be displayed.

songs = { 'red':'All Too Well', 1989: 'Style', 'reputation' : 'Gorgeous'}
y = songs.keys()
songs['folklore'] = 'cardigan'
print(y)
Enter fullscreen mode Exit fullscreen mode

Output:

dict_keys(['red', 1989, 'reputation', 'folklore'])
Enter fullscreen mode Exit fullscreen mode

Determining if a key exists in Dictionary

d = {'red':'All Too Well', 1989: 'Style', 'reputation' : 'Gorgeous'}
if 'red' in d:
    print('yup')
Enter fullscreen mode Exit fullscreen mode

Output:

yup
Enter fullscreen mode Exit fullscreen mode

Adding Elements

For adding a new element in a dictionary, we have to add a key and then assign a value in that key and it will add by default as the last value.

pdict = { 88017:'rihan', 'nila': 2345, 1989: 'Style', 88015:'kiran'}
pdict['mouly'] = 'cse'
print(pdict)
Enter fullscreen mode Exit fullscreen mode

Output:

{88017: 'rihan', 'nila': 2345, 1989: 'Style', 88015: 'kiran', 'mouly': 'cse'}
Enter fullscreen mode Exit fullscreen mode

Update method

Or, we can use update method.

pdict = { 88017:'rihan', 'nila': 2345, 1989: 'Style', 88015:'kiran'}
pdict.update({'mouly' : 'cse'})
print(pdict)
Enter fullscreen mode Exit fullscreen mode

Output:

{88017: 'rihan', 'nila': 2345, 1989: 'Style', 88015: 'kiran', 'mouly': 'cse'}
Enter fullscreen mode Exit fullscreen mode

Del method

We can use del method for removing an element or simply remove the whole dictionary.

rdict = {'darla': 23, 'remina': 45, 'sonam': 3, 'kiran': 44}
del rdict
print(rdict)
Enter fullscreen mode Exit fullscreen mode

Output:

NameError: name 'rdict' is not defined
Enter fullscreen mode Exit fullscreen mode

For removing any selective element from a dictinary,

rdict = {'darla': 23, 'remina': 45, 'sonam': 3, 'kiran': 44}
del rdict['sonam'] 
print(rdict)
Enter fullscreen mode Exit fullscreen mode

Output:

{'darla': 23, 'remina': 45, 'kiran': 44}
Enter fullscreen mode Exit fullscreen mode

Sorting dictionary

We can sort keys or values by using following method.

jdict = {'saturn': 'sat', 'moon': 'ear', 'mars': 'red', 'venus': 2}
new = sorted(jdict.keys())
print(jdict)
print(new)
Enter fullscreen mode Exit fullscreen mode

Output:

['mars', 'moon', 'saturn', 'venus']
Enter fullscreen mode Exit fullscreen mode
m_zen = { 88017:'rihan', 88015:'kiran', 88018 : ['sonam','riki'], 88013: 'harmeonie', 88016 :{24: 'chinal',26:'sonu'}}
y = sorted(m_zen.keys())
print(y)
Enter fullscreen mode Exit fullscreen mode

Output:

[88013, 88015, 88016, 88017, 88018]
Enter fullscreen mode Exit fullscreen mode

Sorting values,

jdict = {'saturn': 'sat', 'moon': 'ear', 'mars': 'red', 'venus': 2}
new = sorted(jdict.values())
print(new)
Enter fullscreen mode Exit fullscreen mode

Output:

TypeError: '<' not supported between instances of 'int' and 'str'
Enter fullscreen mode Exit fullscreen mode

Important thing to notice, we can not compare between the instances of integer and string.

gdict = {'saturn': 'sat', 'moon': 'ear', 'mars': 'red', 'venus': 'blue'}
new = sorted(gdict.values())
print(new)
Enter fullscreen mode Exit fullscreen mode

Output:

['blue', 'ear', 'red', 'sat']
Enter fullscreen mode Exit fullscreen mode

Take a input dict from the user

n = 2
d = dict(input("Enter: ").split() for i in range(n))        #while taking input write one key-value in only line and go to the next line
print(d)
Enter fullscreen mode Exit fullscreen mode

Output:

Enter: name mouly
Enter: student bracu
{'name': 'mouly', 'student': 'bracu'}
Enter fullscreen mode Exit fullscreen mode

or,

val="""name mouly
age 21
home bogura"""

y = dict(x.split() for x in val.splitlines())
print(y)
Enter fullscreen mode Exit fullscreen mode

Output:

{'name': 'mouly', 'age': '21', 'home': 'bogura'}
Enter fullscreen mode Exit fullscreen mode

or,

n = int(input("enter a n value:"))
d = {}
for i in range(n):
    keys = input()           # here i have taken keys as strings
    values =input()          # here i have taken values as integers
    d[keys] = values
print(d)
Enter fullscreen mode Exit fullscreen mode

Output:

enter a n value:2
name
mouly
age
21
{'name': 'mouly', 'age': '21'}
Enter fullscreen mode Exit fullscreen mode

or,

n = int(input())            #n is the number of items you want to enter
d ={}                     
for i in range(n):        
    text = input().split()     #split the input text based on space & store in the list 'text'
    d[text[0]] = text[1]       #assign the 1st item to key and 2nd item to value of the dictionary
print(d)
Enter fullscreen mode Exit fullscreen mode

Output:

2
name mouly
street 2
{'name': 'mouly', 'street': '2'}
Enter fullscreen mode Exit fullscreen mode

Discussion (2)

Collapse
shubham2270 profile image
Shubham Kumar

& it's called Objects in Javascript world 😅

Collapse
mouly22 profile image
Umme Abira Azmary Author

Don't have enough knowledge in Js.. Thanks for letting me know 😅 @shubham Kumar