You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6.1 KiB

Dictionary

In [1]:
d = dict()
In [2]:
d
Out[2]:
{}
In [3]:
d = { 'software' : 10 }
In [4]:
d
Out[4]:
{'software': 10}
In [5]:
d['software']
Out[5]:
10
In [6]:
d[10]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-6-76a0c2738598> in <module>
----> 1 d[10]

KeyError: 10
In [7]:
d['language'] = 6
In [8]:
d
Out[8]:
{'software': 10, 'language': 6}
In [11]:
word = 'hello'
if word in d:
    print(f'{word} is in the dictionary')
else: 
    print(f'{word} is not in the dictionary')
hello is not in the dictionary
In [12]:
d.sort()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-a6324fc0ae3a> in <module>
----> 1 d.sort()

AttributeError: 'dict' object has no attribute 'sort'

Sort a dictionary

In [19]:
list_of_keys = d.keys()
In [20]:
list_of_keys
Out[20]:
dict_keys(['software', 'language'])
In [26]:
keys = []
# key : value
for key, value in d.items():
    keys.append(key)
In [27]:
keys.sort()
In [28]:
keys
Out[28]:
['language', 'software']
In [32]:
for key in keys:
    print(f'{key} is here so many times:', d[key])
language is here so many times: 6
software is here so many times: 10
In [ ]:
 
In [ ]:
 
In [ ]: