Create dictionary in python using tuples, lists, key,value pairs and json

Dictionary is one of the important data types in python. A dictionary will have a key and a value and the keys should be unique. A typical dictionary would look like this.

data = {
    "first_name": "Abraham",
    "last_name": "Lincoln",
    "job": "President"

In this article we are going to see the other methods of creating a dictionary. The three methods are

  1. Creating dictionary from tuples
  2. Creating dictionary from two lists(values from one list as key and another one as value).
  3. Creating dictionary from key value pairs.

Creating dictionary from tuples

A tuple will have values separated by “,” and enclosed by ‘()’ brackets. We can use a list of tuples with two values one being the key and another being the value to create a dictionary like this.

dictionary using tuples

Creating dictionary using key value pairs

A key, value pair can also be converted into dictionary by type casting the key, value pair to a dictionary. This can be done by the following way.

Create dictionary from two lists

The zip method can be used to combine two lists two form dictionary. This will return a zip object which can be type casted to a dictionary.

consider two lists like this.

key = ['first_name', 'last_name', 'job']
value = ['Abraham', 'Lincoln']

The first value from the first list will be used as the first key and the first value from the second list will be used as the value for the first key and so on. This will work for the number of matching indexes in the both the list. If one list has 5 values and the other has 3 values. The dictionary will be created only with 3 key, value pairs as the remaining two keys wont have any values.

zip method to create dictionary

Let us look at one more example with two lists of different lengths.

The output of this code snippet is also the same as the first code snippet. Since the first list has 3 values and the second list has only 2 arguments the 3rd value in the first list is ignored.

Create dictionary from json data

We can also create dictionary from a json data. Moreover they both are similar in structure. The only difference is the json will be of string data type.

we can use the loads() method from the json module to convert the json string to dictionary. loads() is jsut load from string or load string.

dictionary from a json file

We need to use the load() method if we are going to load the json from an external file like this.

dictionary from an external json file

Hope you have learnt new ways to create dictionary from this article.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *