DEV Community

haytam_7
haytam_7

Posted on • Updated on

Key and Value

dictionary_data = {'Changeable': 'Yes', 'Unordered': 'Yes', 'Duplicates': 'No'}

And as simplicity continues while learning Python, it's time to talk about a unique way of saving data in Python using something called DICTIONARY.

Dictionary is based on the principle of key-value

Like when you want to search for a word definition in the dictionary, you search for the word, in Python dictionaries you search for the KEY to get the VALUE.

Let's take a look at a basic syntax of a dictionary which represents a stored data for names and ages of two people:

names_ages = {'Oliver': 20, 'George': 23}

Oliver and George are the keys, 20 and 23 are the values.

Getting a value:

names_ages['Oliver'] 
will return 20.
Enter fullscreen mode Exit fullscreen mode

Adding a new key and value:

names_ages['Michael'] = 24

Enter fullscreen mode Exit fullscreen mode

Updating a value:

names_ages['Oliver'] = 30
Enter fullscreen mode Exit fullscreen mode

Removing an entire element:

del names_ages['Oliver']
Enter fullscreen mode Exit fullscreen mode

(Now Oliver the key and its value are removed)

If you want to print each pair separated by a comma you can use the items() method:

print(names_ages.items())
Enter fullscreen mode Exit fullscreen mode

Top comments (0)