Python Dictionaries and JSON

2020-08-01 13:14:30 | #programming #python | Part 4 of 7

Up until now, we've been using singular values to represent our data. A Python dictionary is a data type that allows us to give our data a more complex structure.

We will no longer be limited by simple variables like color = 'red'. Rather, we can represent an object with with a dictionary that contains more information about an object. For example, we can define all the properties of a person using a person dictionary:

person = {
    'hair_color': 'red',
    'eye_color': 'green',
    'height': '165cm',
    'first_name': 'Jane',
    'last_name': 'Doe',
    'age': 27
}

Python Dictionaries

A Python dictionary is formatted with curly braces, keys and values, like so:

mydict = {
    'key1': 'Value 1',
    'key2': 'Value 2',
    'key3': 'Value 3'
}

With this key/value structure, dictionaries are much more human-readable and provides us with a more intuitive way to access values. Take a look at the following example, where we define a book dictionary:

Try It Yourself


 
  

As you can see, we access values by referencing book's key name. Notice how we can define our own custom key names ('title', 'author', etc.). Keys must use the string data type and we can add as many as needed. Values can be any data type. In the above example, we have some string values and a number value for pages. Here's an example with a list value:

Try It Yourself


 
  

Because genres is a list, we have to access each element by its index. A Python dictionary can even contain a dictionary, and/or list of dictionaries, as deep as we need to go.

Try It Yourself


 
  

We can even represent a collection of books by storing multiple dictionaries into a list:

Try It Yourself


 
  

Python Dictionary Metadata

Did you know you can access the length of a dictionary? You can also check if a Python dictionary contains a key. Take a look at the following examples:

Try It Yourself


 
  

Modifying a Python Dictionary

You can also modify, add to and remove from a dictionary, as demonstrated by the following examples:

Try It Yourself


 
  

JSON

JSON stands for JavaScript Object Notation, and is structurally very similar to Python dictionaries. They are both human-readable and utilize key value pairs. The main difference is that JSON is a text string that is meant to be transmitted between servers/programs across different programming languages. Using the JSON standard, Java, Python, JavaScript, etc., programs can speak with each other. Python can use a Dictionary internally, convert it to JSON, and transmit it to a JavaScript program which will then convert it to a JavaScript Object.

To convert json to a dictionary, we can use json.loads() and to convert a dictionary to json, we use json.dumps()

import json

json_data = '{"title":"Snow Crash", "author": "Neal Stephenson"}'

book = {'title': 'Nineteen Eighty-Four',
        'author': 'George Orwell',
        'country': 'United Kingdom',
        'pages': 328,
        'genres': ['dystopian', 'political fiction'],
        'publisher': {
            'name': 'Secker & Warburg',
            'date': '1949-06-08 00:00:00'}
        }


if __name__ == '__main__':
    dict_book = json.loads(json_data)
    print(dict_book)

    json_book = json.dumps(book)
    print(json_book)

Python Programming Exercises

Try to solve the following problems, using everything you've learned up to this point. Feel free to share solutions in the comments. Optimize each solution, as much as possible.

  1. Add a key to a dictionary using Python

    Input: {'key1': 'Value 1'}

    Expected Output: {'key1': 'Value 1', 'key2': 'Value 2'}

    Try It Yourself


     
              
  2. Return a list containing a dictionary's keys using Python

    Input: {'key1': 'Value 1', 'key2': 'Value 2'}

    Expected Output: ['key1', 'key2']

    Try It Yourself


     
              
  3. Return a list containing a dictionary's values using Python

    Input: {'key1': 'Value 1', 'key2': 'Value 2'}

    Expected Output: ['Value 1', 'Value 2']

    Try It Yourself


     
              
  4. Write a Python list comprehension to convert a list of tuple coordinates into a list of dictionaries

    Input: [(3, 45), (5, 2), (32, 3)]

    Expected Output: [{'x': 3, 'y': 45}, {'x': 5, 'y': 2}, {'x': 32, 'y': 3}]

    Try It Yourself


     
              
  5. Write a Python list comprehension to filter a list of dictionaries by value. For example, in the following list, pull out the dictionaries where x = 5

    Input: [{'x': 3, 'y': 45}, {'x': 5, 'y': 2}, {'x': 32, 'y': 3}, {'x': 5, 'y': 6}]

    Expected Output: [{'x': 5, 'y': 2}, {'x': 6, 'y': 6}]

    Try It Yourself


     
              

Conclusion

That's the end of this tutorial. We hope you found it helpful. Make sure to check out our other tutorials, as well.

If you're interested in programs that carry out your computer tasks for you, take our Automation the Easy Way with Python course. This course teaches CSV and Excel file generation, API requests, website scraping, email delivery, task scheduling, and browser click, mouse, and keyboard automation. Automate your daily tasks, free up time, and get ahead, today.

Want To See More Exercises?

View Exercises View Courses

Comments

You must log in to comment. Don't have an account? Sign up for free.

Subscribe to comments for this post

Want To Receive More Free Content?

Would you like to receive free resources, tailored to help you reach your IT goals? Get started now, by leaving your email address below. We promise not to spam. You can also sign up for a free account and follow us on and engage with the community. You may opt out at any time.



Tell Us About Your Project









Contact Us

Do you have a specific IT problem that needs solving or just have a general IT question? Use the contact form to get in touch with us and an IT professional will be with you, momentarily.

Hire Us

We offer web development, enterprise software development, QA & testing, google analytics, domains and hosting, databases, security, IT consulting, and other IT-related services.

Free IT Tutorials

Head over to our tutorials section to learn all about working with various IT solutions.

Contact