Read from dictionary python

Get value from dictionary by key with get() in Python

This article describes how to get the value from a dictionary ( dict type object) by the key in Python.

If you want to extract keys by their values, see the following article.

Get value from dictionary with dictRead from dictionary python ( KeyError for non-existent keys)

In Python, you can get the value from a dictionary by specifying the key like dictRead from dictionary python .

d = 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'> print(d['key1']) # val1 

In this case, KeyError is raised if the key does not exist.

# print(d['key4']) # KeyError: 'key4' 

Specifying a non-existent key is not a problem if you want to add a new element.

For more information about adding items to the dictionary, see the following article.

Use in to check if the key exists in the dictionary.

Use dict.get() to get the default value for non-existent keys

You can use the get() method of the dictionary ( dict ) to get any default value without an error if the key does not exist.

Specify the key as the first argument. If the key exists, the corresponding value is returned; otherwise, None is returned.

d = 'key1': 'val1', 'key2': 'val2', 'key3': 'val3'> print(d.get('key1')) # val1 print(d.get('key4')) # None 

You can specify the default value to be returned when the key does not exist in the second argument.

print(d.get('key4', 'NO KEY')) # NO KEY print(d.get('key4', 100)) # 100 

The original dictionary remains unchanged.

Источник

Python Save Dictionary To File

In this lesson, you’ll learn how to save a dictionary to a file in Python. Also, we’ll see how to read the same dictionary from a file.

In this lesson, you’ll learn how to:

  • Use the pickle module to save the dictionary object to a file.
  • Save the dictionary to a text file.
  • Use the dump() method of a json module to write a dictionary in a json file.
  • Write the dictionary to a CSV file.

Table of contents

How to save a dictionary to file in Python

Dictionaries are ordered collections of unique values stored in (Key-Value) pairs. The below steps show how to use the pickle module to save the dictionary to a file.

    Import pickle module The pickle module is used for serializing and de-serializing a Python object structure.

Pickling” is the process whereby a Python object is converted into a byte stream, and “unpickling” is the inverse operation whereby a byte stream (from a binary file) is converted back into an original object.

Example: save a dictionary to file

Let’s see the below example of how you can use the pickle module to save a dictionary to a person_data.pkl file.

import pickle # create a dictionary using <> person = print('Person dictionary') print(person) # save dictionary to person_data.pkl file with open('person_data.pkl', 'wb') as fp: pickle.dump(person, fp) print('dictionary saved successfully to file')
Person dictionary dictionary saved successfully to file

Read Dictionary from a File

Now read the same dictionary from a file using a pickle module’s load() method.

import pickle # Read dictionary pkl file with open('person_data.pkl', 'rb') as fp: person = pickle.load(fp) print('Person dictionary') print(person)

Save a dictionary to a text file using the json module

We can use the Python json module to write dictionary objects as text data into the file. This module provides methods to encode and decode data in JSON and text formats.

We will use the following two methods of a json module.

  • The dump() method is used to write Python objects as JSON formatted data into a file.
  • Using the load() method, we can read JSON data from text, JSON, or a binary file to a dictionary object.

Let’s see the below example of how you can use the json module to save a dictionary to a text file.

import json # assume you have the following dictionary person = print('Person dictionary') print(person) print("Started writing dictionary to a file") with open("person.txt", "w") as fp: json.dump(person, fp) # encode dict into JSON print("Done writing dict into .txt file")
Person dictionary Started writing dictionary to a file Done writing dict into .txt file

Person text file

Note: You can also use the dump() method to write a dictionary in a json file. Only you need to change the file extension to json while writing it.

Read a dictionary from a text file.

Now, let’s see how to read the same dictionary from the file using the load() function.

import json # Open the file for reading with open("person.txt", "r") as fp: # Load the dictionary from the file person_dict = json.load(fp) # Print the contents of the dictionary print(person_dict)

Save the dictionary to a CSV file

The Python csv library provides functionality to read from and write to CSV files.

  • Use the csv.DictReader() method to read CSV files into a dictionary.
  • Use the csv.DictWriter() method to write a dictionary to a CSV file.

Example: Save the dictionary to a CSV file.

import csv # Dictionary to be saved person = print('Person dictionary') print(person) # Open a csv file for writing with open("person.csv", "w", newline="") as fp: # Create a writer object writer = csv.DictWriter(fp, fieldnames=person.keys()) # Write the header row writer.writeheader() # Write the data rows writer.writerow(person) print('Done writing dict to a csv file')
Person dictionary Done writing dict to a csv file

Person csv file

Example: Read a dictionary from a csv file

import csv # Open the csv file for reading with open("person.csv", "r") as infile: # Create a reader object reader = csv.DictReader(infile) # Iterate through the rows for row in reader: print(row)
OrderedDict([('name', 'Jessa'), ('country', 'USA'), ('telephone', '1178')])

Note: This will read the contents of the person.csv file and create a dictionary for each row in the file. You can then iterate through the rows and access the values in the dictionary using the column names as keys.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

How to extract all values from a dictionary in Python

In this Python tutorial, we will understand how to get all values from a dictionary in Python.

We can get all values from a dictionary in Python using the following 5 methods.

  1. Using dict.values()
  2. Using * and dict.values()
  3. Using for loop & append()
  4. Using the map() function
  5. Using list comprehension & dict.values()

Get all values from a dictionary Python

Here we will illustrate multiple methods to get all values from a Python Dictionary. And for this, we will start with the dict.values() method.

Method 1: Using dict.values()

The dict.values() in Python is a Dictionary method that fetched all the values from the dictionary and returns a dict_values object. This object contains all the values of a dictionary.

However, we can easily convert this dict_values object into a list using the list() constructor in Python.

Here is an example of this approach in Python.

# Defining a dictionary Countries = < 6:'Canada', 2:'United Kingdom', 1:'United States', 9:'Australia', 7:'China' ># Fetching all dictionary values country_names = list(Countries.values()) # Printing all dictionary values print(country_names)

In the example, we are fetching all the values from the Countries dictionary using the dict.values() method. After this, convert the result of the dict.values() method into a list using list() function.

The result of the Python program is shown below.

['Canada', 'United Kingdom', 'United States', 'Australia', 'China']

Method 2: Using * and dict.values()

Alternatively, we can also use the * operator with the dict.values() method to fetch all the values from a dictionary in Python.

Here is an example of this execution in python.

# Defining a dictionary in Python user_data = < 'Name': 'Alex', 'Age': 32, 'City': 'Chicago', 'Country': 'United States', 'Technical Skills': ['SQL', 'Java'] ># Fetching all dictionary values user_values = [*user_data.values()] # Printing all dictionary values print(user_values)

In this example, we utilized the * operator with dict.values() to fetch all the values from the user_data dictionary.

['Alex', 32, 'Chicago', 'United States', ['SQL', 'Java']]

Method 3: Using for loop & append()

In this method, we will use the for loop to iterate over each dictionary value using dict.values(). And then we use the append() method to store the value in a Python List.

The execution related to this approach is given in the Python code below.

# Defining a dictionary Countries = < 6:'Canada', 2:'United Kingdom', 1:'United States', 9:'Australia', 7:'China' ># Defining empty dictionary country_names = [] # Fetching all dictionary values for value in Countries.values(): country_names.append(value) # Printing all dictionary values print(country_names)
  • In this example, we used for loop over the Countries.values() and fetch each dictionary value.
  • After this, we used the append() method on the country_names list to store every dictionary value in it.

The result of the Python program is given below.

['Canada', 'United Kingdom', 'United States', 'Australia', 'China']

Method 4: Using list comprehension & dict.values()

  • In this method, we used the same dict.values() method to fetch all the dictionary values as dict_values object.
  • Then we used the concept of list comprehension to generate a new list using the result of dict.values().
# Defining a dictionary in Python countries_hdi = < 'Canada': 0.937, 'United Kingdom': 0.935, 'United States': 0.921, ># Fetching all dictionary values hdi_values = [value for value in countries_hdi.values()] # Printing all dictionary values print(hdi_values)

Here we used the countries_hdi.values() method to get all list of values from countries_hdi dictionary. And we also used list comprehension using the countries_hdi.values() method.

This will result in forming another list named hdi_values containing all the values from the countries_hdi dictionary values. Once we print the hdi_values list, we will get the following result.

Method 5: Using the map() function

Another way to get all values from a Python Dictionary is by using the map() function with dict.get() method.

The dict.get() function in Python allows fetching the value of a particular key given in a dictionary. On the other hand, the map() function allows to execution of a function for each value given in an iterable.

So, in this approach, we will fetch all the keys from a dictionary and use each key name with map() and dict.get() function. This allows fetching each value corresponding to a key in Dictionary.

An example of this approach is shown in the code below.

# Defining a dictionary in Python user_data = < 'Name': 'Alex', 'Age': 32, 'City': 'Chicago', 'Country': 'United States', 'Technical Skills': ['SQL', 'Java'] ># Fetching all dictionary values keys = list(user_data.keys()) user_values = list(map(user_data.get, keys)) # Printing all dictionary values print(user_values)

Once we execute the above Python program, we will get the following result.

Get all values from a dictionary Python

You may also like to read the following Python tutorials.

Conclusion

So, in this Python tutorial, we understood how to fetch or get all values from a dictionary Python. Additionary, we have covered 5 different methods for this task and each method covers an example.

The 5 ways that we covered are given below.

  1. Get all values from a dictionary Python using dict.values()
  2. Get all values from a dictionary Python using * and dict.values()
  3. Get all values from a dictionary Python using for loop & append()
  4. Get all values from a dictionary Python using the map() function
  5. Get all values from a dictionary Python using list comprehension & dict.values()

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Читайте также:  Repeating image html code
Оцените статью