Create new dictionary python

Python : 6 Different ways to create Dictionaries

In this article, we will discuss different ways to create dictionary objects in python.

What is a dictionary?

dictionary is an associative container that contains the items in key/value pairs. For example, we if want to track the words and their frequency count in an article like,

“Hello” occurs 7 times
“hi” occurs 10 times
“there” occurs 45 times
“at” occurs 23 times
“this” occurs 77 times

We can use the python dictionary to keep this data, where the key will the string word and value is the frequency count.

Frequently Asked:

Now let’s see different ways to create a dictionary,

Creating Empty Dictionary

We can create an empty dictionary in 2 ways i.e.

''' Creating empty Dictionary ''' # Creating an empty dict using empty brackets wordFrequency = <> # Creating an empty dict using dict() wordFrequency = dict()

It will create an empty dictionary like this,

Читайте также:  Creating application form in html

Creating Dictionaries with literals

We can create a dictionary by passing key-value pairs literals i.e.

»’ Creating Dictionaries with literals »’ wordFrequency =

It will create a dictionary like this,

Creating Dictionaries by passing parameters in dict constructor

We can create a dictionary by passing key-value pairs in dictionary constructor i.e.

''' Creating Dictionaries by passing parametrs in dict constructor ''' wordFrequency = dict(Hello = 7, hi = 10, there = 45, at = 23, this = 77 )

It will create a dictionary like this,

Creating Dictionaries by a list of tuples

# List of tuples listofTuples = [("Hello" , 7), ("hi" , 10), ("there" , 45),("at" , 23),("this" , 77)]

We can create a dict out of this list of tuple easily by passing it in constructor i.e.

# Creating and initializing a dict by tuple wordFrequency = dict(listofTuples)

It will create a dictionary like this,

Creating a Dictionary by a list of keys and initializing all with the same value

Suppose we have a list of string i.e.

listofStrings = ["Hello", "hi", "there", "at", "this"]

Now we want to create a dictionary where all the elements of the above list will be keys and their default value is 0.
We can do that using fromkeys() function of dict i.e.

# create and Initialize a dictionary by this list elements as keys and with same value 0 wordFrequency = dict.fromkeys(listofStrings,0 )

It will Iterate over the list of string and for each element, it will create a key-value pair with value as default value provided and store them in dict.

It will create a dictionary like this,

Creating a Dictionary by two lists

Suppose we have two lists i.e.

# List of strings listofStrings = ["Hello", "hi", "there", "at", "this"]

List of integers,

# List of ints listofInts = [7, 10, 45, 23, 77]

Now we want to use elements in the list of string as keys and items in the list of ints as value while creating a dictionary.
To do that we are going to use zip() function that will Iterate over the two lists in parallel.

For each entry in the list, it will create a key-value pair and finally create a zipped object. Now, we can pass this zipped object to dict() to create a dictionary out of it i.e.

# Merge the two lists to create a dictionary wordFrequency = dict( zip(listofStrings,listofInts ))
# Merge the two lists to create a dictionary wordFrequency = dict( zip(listofStrings,listofInts ))

It will create a dictionary like this,

Python Dictionary Tutorial — Series:

  1. What is a Dictionary in Python & why do we need it?
  2. Creating Dictionaries in Python
  3. Iterating over dictionaries
  4. Check if a key exists in dictionary
  5. Check if a value exists in dictionary
  6. Get all the keys in Dictionary
  7. Get all the Values in a Dictionary
  8. Remove a key from Dictionary
  9. Add key/value pairs in Dictionary
  10. Find keys by value in Dictionary
  11. Filter a dictionary by conditions
  12. Print dictionary line by line
  13. Convert a list to dictionary
  14. Sort a Dictionary by key
  15. Sort a dictionary by value in descending or ascending order
  16. Dictionary: Shallow vs Deep Copy
  17. Remove keys while Iterating
  18. Get all keys with maximum value
  19. Merge two or more dictionaries in python

Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.

The complete example is as follows,

def main(): ''' Creating empty Dictionary ''' # Creating an empty dict using empty brackets wordFrequency = <> # Creating an empty dict using dict() wordFrequency = dict() print(wordFrequency) ''' Creating Dictionaries with literals ''' wordFrequency = < "Hello" : 7, "hi" : 10, "there" : 45, "at" : 23, "this" : 77 >print(wordFrequency) ''' Creating Dictionaries by passing parametrs in dict constructor ''' wordFrequency = dict(Hello = 7, hi = 10, there = 45, at = 23, this = 77 ) print(wordFrequency) ''' Creating Dictionaries by a list of tuples ''' # List of tuples listofTuples = [("Hello" , 7), ("hi" , 10), ("there" , 45),("at" , 23),("this" , 77)] # Creating and initializing a dict by tuple wordFrequency = dict(listofTuples) print(wordFrequency) ''' Creating Dictionary by a list of keys and initialzing all with same value ''' listofStrings = ["Hello", "hi", "there", "at", "this"] # create and Initialize a dictionary by this list elements as keys and with same value 0 wordFrequency = dict.fromkeys(listofStrings,0 ) print(wordFrequency) ''' Creating a Dictionary by a two lists ''' # List of strings listofStrings = ["Hello", "hi", "there", "at", "this"] # List of ints listofInts = [7, 10, 45, 23, 77] # Merge the two lists to create a dictionary wordFrequency = dict( zip(listofStrings,listofInts )) print(wordFrequency) if __name__ == "__main__": main()

Источник

5 Ways to Create a Dictionary in Python

So, you’ve already figured out how to use dictionaries in Python. You know all about how dictionaries are mutable data structures that hold key-value pairs. You understand you must provide a key to the dictionary to retrieve a value. But you may not have realized dictionaries in Python come in all shapes and sizes and from all kinds of sources.

Just think about how many real-life objects can be modeled using key-value pairs: students and their grades, people and their occupations, products and their prices, just to name a few. Dictionaries are central to data processing in Python, and you run into them when loading data from files or retrieving data from the web.

Since Python dictionaries are so ubiquitous, it is no surprise you can build them from many different sources. In this article, we explore 5 ways to create dictionaries in Python. Let’s get started!

1. Python Dictionary From the Dictionary Literal <>

Not surprisingly, this is the most common method for creating dictionaries in Python. All you have to do is declare your key-value pairs directly into the code and remember to use the proper formatting:

Simple, but effective! Here’s a basic example of how this looks:

Dictionaries ignore spaces and line breaks inside them. We can take advantage of this and write just one key-value pair per line. It improves readability, especially when our dictionaries grow a little too big to fit comfortably in a single line:

2. Python Dictionary From the dict() Constructor

Dictionaries can also be built from the Python dict() constructor. dict() is a built-in function in Python, so it is always available to use without the need to import anything.

You can use the Python dict() constructor in two ways. The first is to provide the key-value pairs through keyword arguments:

prices = dict(apple=2.5, orange=3.0, peach=4.4) print(prices) # output:

It’s fair to say the first method is easier to read and understand at a glance. However, keyword arguments are always interpreted as strings, and using keyword arguments may not be an option if you need a dictionary in which the keys are not strings. Take a look at this example to see what I mean:

# this works values = [(1, 'one'), (2, 'two')] prices = dict(values) # SyntaxError - a number is not a valid keyword argument! prices = dict(1='one', 2='two')

By the way, if you need a reminder, check out this great article on tuples and other sequences in Python.

3. Python Dictionary From a JSON File

JSON stands for JavaScript Object Notation, and it is an extremely common file format for storing and transmitting data on the web. Here’s an example JSON file, called person.json :

Notice anything? Yep! JSON files are pretty much identical to dictionaries in Python. So, it is no surprise you can load JSON data into Python very easily. We simply need to:

  • Import the json module (don’t worry about installing anything; this module is part of Python’s base installation).
  • Open the person.json file (take a look at this course if you don’t know what “opening a file” means in Python).
  • Pass the open file handle to the json.load() function.

We take these steps in the code below:

import json with open(‘person.json’, ‘r’) as json_file: person = json.load(json_file) print(person) # output:

Note that you can also go the other way around and write a Python dict() into a JSON file. This process is called serialization. See this article for more information about serialization.

4. Python Dictionary From Two Dictionaries Using the Dictionary Union Operator

If you’re using Python version 3.9 or greater, there’s yet another way to create a dictionary in Python: the dictionary union operator ( | ), introduced in Python 3.9. It merges the key-value pairs of two or more dictionaries into a single one. In that sense, it is similar to the set union operator (read this article if you don’t know what set operators are).

Here’s an example of the dictionary union operator in action:

jobs_1 = < 'John': 'Engineer', 'James': 'Physician', >jobs_2 = < 'Jack': 'Journalist', 'Jill': 'Lawyer', >jobs = jobs_1 | jobs_2 print(jobs) # output:

It’s important to note that, if there are duplicate keys in the source dictionaries, the resulting dictionary gets the value from the right-most source dictionary. This is a consequence of Python not allowing duplicate keys in a dictionary. Take a look at what happens here:

d1 = < 'A': 1, 'B': 2, >d2 = < 'B': 100, 'C': 3, >result = d1 | d2 print(result) # output:

As you can see, B appears in both d1 and d2 . The value in the result dictionary comes from d2 , the right-most source dictionary in the expression d1 | d2 . The key-value pair ‘B’: 2 from d1 is lost. Keep this in mind when using the dictionary union operator!

5. Python Dictionary From a Dict Comprehension

Have you heard of list comprehensions? Once you get the hang of them, they are a great way to create new lists from already existing ones, either by filtering the elements or modifying them.

But what does it have to do with building dictionaries in Python? Well, a similar syntax is used for constructing dictionaries, in what we call a dict comprehension. In the example below, we take a list of strings and build a dictionary from them. Each key is the string itself, and the corresponding value is its length. Take a look:

animals = [‘cat’, ‘lion’, ‘monkey’] animal_dict = print(animal_dict) # output:

See how it works? For each animal in the list animals , we build a key-value pair of the animal itself and its length ( len(animal) ).

Here’s a more intricate example. We use a dict comprehension to filter the values from a preexisting dictionary. See if you can figure out what the code below does:

ages = < 'Bill': 23, 'Steve': 34, 'Maria': 21, >filtered_ages = print(filtered_ages) # output:

Create Dictionaries in Python!

In this article, we discussed 5 ways to create dictionaries in Python. We went from the very basics of the dictionary literal <> and the Python dict() constructor, to more complex examples of JSON files, dictionary union operators, and dict comprehensions.

Hope you learned something new. If you want more, be sure to go to LearnPython.com for all things related to Python!

Источник

Оцените статью