Key and Value

haytamkh7

haytam_7

Posted on December 24, 2020

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
💖 💪 🙅 🚩
haytamkh7
haytam_7

Posted on December 24, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related