Showing posts with label dictionary. Show all posts
Showing posts with label dictionary. Show all posts

Wednesday, 7 February 2024

Pretty print dictionary content in Python

Approach 1: Writing custom function.

pretty_print_dictionary.py

def pretty_print_dict(dict, indent=0):
    for key, value in dict.items():
        if isinstance(value, dict):
            print(' ' * indent + str(key) + ':')
            pretty_print_dict(value, indent + 4)
        else:
            print(' ' * indent + str(key) + ': ' + str(value))

# Example usage:
address = {'city' : 'Banaglore', 'state' : 'Karnataka', 'country' : 'India'}
employee = {'name' : 'Krishna', 'age' : 34, 'address' : address}

pretty_print_dict(employee)

Output

name: Krishna
age: 34
address:
    city: Banaglore
    state: Karnataka
    country: India

In the above snippet, pretty_print_dict function takes a dictionary ‘dict’ as input and prints it in a human-readable format, with nested dictionaries indented by 4 spaces. You can adjust the indentation by modifying the indent parameter.

 

Approach 2: Using pprint module.

Using ‘pprint’ module, we can print the dictionary content in pretty formant Python.

 

pretty_print_dict.py

import pprint

address = {'city' : 'Bangalore', 'state' : 'Karnataka', 'country' : 'India'}
employee = {'name' : 'Krishna', 'age' : 34, 'address' : address}

pprint.pprint(employee)

Output

{'address': {'city': 'Bangalore', 'country': 'India', 'state': 'Karnataka'},
 'age': 34,
 'name': 'Krishna'}

This Python snippet demonstrates the use of the pprint module to pretty-print a nested Python dictionary.

 

import pprint

This line imports the pprint module, which contains the pprint() function. This function is used to print Python data structures in a way that's more readable than the standard print function.

 

pprint.pprint(employee)

This line calls the pprint() function from the pprint module to print the employee dictionary. The pprint function formats the output in a more readable way, especially useful for nested or complex data structures.

 

Approach 3: Using json module.

You can use the json module in Python to pretty print dictionary content. Here's a simple example:

 

pretty_print_dict_by_json_module.py

import json
def pretty_print_dict(dict, indent=0):
   return json.dumps(dict, indent=4)

# Example usage:
address = {'city' : 'Banaglore', 'state' : 'Karnataka', 'country' : 'India'}
employee = {'name' : 'Krishna', 'age' : 34, 'address' : address}

print(pretty_print_dict(employee))

Output

{
    "name": "Krishna",
    "age": 34,
    "address": {
        "city": "Banaglore",
        "state": "Karnataka",
        "country": "India"
    }
}

The indent parameter in json.dumps() is used to specify the indentation level for the output, making it easier to read.


Previous                                                 Next                                                 Home

Tuesday, 6 February 2024

Python's setdefault(): A Shortcut for Adding Keys with Defaults

The ‘setdefault()’ method is a dictionary method in Python that checks for a key's existence and assigning a default value if the key is not exists in the dictionary.

 

Its functionality can be summarized as follows:

 

a.   If the specified key already exists in the dictionary, the method returns the corresponding value associated with that key.

b.   If the key does not exist in the dictionary, setdefault() adds the key to the dictionary with the provided default value and then returns this default value.

 

set_default_value.py

def wordCount(str):
    dict = {}

    for word in str.split():
        count = dict.setdefault(word, 0)
        dict[word] = count+1

    return dict

str = '''Word Count Program
Welcome to the Word Count Program! This program will analyze the text you provide and count the number of words in it
'''

print(wordCount(str))

 

Output

{'Word': 2, 'Count': 2, 'Program': 1, 'Welcome': 1, 'to': 1, 'the': 3, 'Program!': 1, 'This': 1, 'program': 1, 'will': 1, 'analyze': 1, 'text': 1, 'you': 1, 'provide': 1, 'and': 1, 'count': 1, 'number': 1, 'of': 1, 'words': 1, 'in': 1, 'it': 1}

 

Above snippet defines a function called 'wordCount' that takes a string (str) as input and returns a dictionary containing the count of each word in the input string.

 

def wordCount(str)

This line defines a function named wordCount that takes a single parameter str, which is the input string.

 

dict = {}

This line initializes an empty dictionary named dict which will store the word counts.

 

for word in str.split()

This line iterates over each word in the input string. str.split() splits the input string into a list of words based on whitespace (spaces, tabs, etc.).

 

count = dict.setdefault(word, 0)

For each word encountered, this line either retrieves its current count from the dictionary dict, or if the word is not already in the dictionary, it sets the count to 0. The setdefault() method returns the value of the specified key if it exists, otherwise it sets the key to the specified value (0 in this case) and returns that value.

 

dict[word] = count+1

This line increments the count for the current word by 1. It updates the value associated with the key word in the dictionary dict.

 

return dict

After counting all the words in the input string, the function returns the dictionary containing the word counts.

 

In summary, this function takes a string as input, splits it into words, counts the occurrences of each word, and returns a dictionary where the keys are the unique words and the values are the counts of each word.

 

Previous                                                 Next                                                 Home

Monday, 5 February 2024

Check for existence of value in a dictionary using in operator in Python

Using both values() method and ‘in’ operator, we can check for the existence of a value in a Dictionary.

Retrieve the values from the dictionary:

Use the values() method to obtain a view object containing all the values stored in the dictionary.

 

Use the in operator

Apply the in operator to this view object to find whether the given value is present within it or not.

 

check_for_value_existence.py

employee = {'id' : 123, 'name' : 'Krishna', 'age' : 34}

if 'krishna' in employee.values():
    print('Krishna is in employee')
else:
    print('Krishna is not in employee')

if 'Ram' in employee:
    print('Ram is in employee')
else:
    print('Ram is not in employee')

Output

Krishna is not in employee
Ram is not in employee

  

Previous                                                 Next                                                 Home

Thursday, 1 February 2024

Check for existence of key in a dictionary using in operator in Python

Using the ‘in’ operator in ‘if’ condition, we can check for the existenace of a key in Python Dictionary.

employee = {'id' : 123, 'name' : 'krishna', 'age' : 34}

if 'id' in employee:
    print('id is in employee')
else:
    print('id is not in employee')

Above snippet defines a dictionary named employee with three key-value pairs representing employee information: 'id' with a value of 123, 'name' with a value of 'krishna', and 'age' with a value of 34.

 

Subsequently, an if statement checks whether the key 'id' exists in the dictionary. If the key is present, it prints 'id is in employee'; otherwise, it prints 'id is not in employee'. In this case, since 'id' is indeed a key in the dictionary, the condition evaluates to True, and the first print statement is executed, displaying 'id is in employee' as the output.

 

Find the below working application.

check_for_key_existence.py

employee = {'id' : 123, 'name' : 'krishna', 'age' : 34}

if 'id' in employee:
    print('id is in employee')
else:
    print('id is not in employee')

if 'city' in employee:
    print('city is in employee')
else:
    print('city is not in employee')

Output

id is in employee
city is not in employee


Previous                                                 Next                                                 Home

Tuesday, 30 January 2024

Looping over the dictionary using items() method in Python

Using items() method, we can iterate over a dictionary.

>>> emp_dict = {'id' : 1, 'name' : 'Krishna', 'age' : 34}
>>> 
>>> for key, value in emp_dict.items():
...   print(f'{key} --> {value}')
... 
id --> 1
name --> Krishna
age --> 34

 

Above code demonstrates how to iterate over a dictionary and print its key-value pairs.

 

emp_dict = {'id' : 1, 'name' : 'Krishna', 'age' : 34}

This line creates a dictionary named emp_dict. A dictionary in Python is a collection of key-value pairs. Here, the dictionary represents an employee with three pieces of information: their 'id' (which is 1), 'name' (which is 'Krishna'), and 'age' (which is 34).

 

for key, value in emp_dict.items():

This line starts a for loop. The .items() method is called on the dictionary emp_dict. This method returns a view object that displays a list of dictionary's (key, value) tuple pairs.

 

In each iteration of the loop, key and value will be assigned to the corresponding pair of items from the dictionary. For instance, in the first iteration, key will be 'id' and value will be 1, in the second iteration, key will be 'name' and value will be 'Krishna', and so on.

 

 

Previous                                                 Next                                                 Home

Saturday, 6 November 2021

Python: dict(): Create a dictionary

‘dict()’ is used to create a dictionary.

 

Example

empDict = dict(name = "Krishna", age = 36, id = 1)

 

create_dict_using_dict_function.py

empDict = dict(name = "Krishna", age = 36, id = 1)

print(empDict)

 

Output

{'name': 'Krishna', 'age': 36, 'id': 1}

 

 

Previous                                                    Next                                                    Home

Sunday, 27 December 2020

Python: List in a dictionary

In this post, I am going to explain how to add a list to the dictionary.

 

list_in_dictionary.py

dict = {1 : "One"}
even_numbers = [2, 4, 6, 8]
odd_numbers = [1, 3, 5, 7]

my_dictionary = {"dict": dict, "evenNumbers" : even_numbers, "oddNumbers" : odd_numbers}

for key in my_dictionary.keys():
	print(f"{key} -> {my_dictionary[key]}")

 

This Python snippet initializes three separate variables: a dictionary named dict with the key-value pair {1: "One"}, a list named even_numbers containing even integers [2, 4, 6, 8], and another list named odd_numbers containing odd integers [1, 3, 5, 7]. Subsequently, a new dictionary named my_dictionary is created, where each key corresponds to a different variable, linking the names 'dict', 'evenNumbers', and 'oddNumbers' to their respective values.

 

The snippet then employs a for loop to iterate through the keys of my_dictionary. Within each iteration, it prints a formatted string indicating the key and its associated value. This loop effectively showcases the contents of my_dictionary by displaying each key-value pair.

 

Output

$ python3 list_in_dictionary.py 
dict -> {1: 'One'}
evenNumbers -> [2, 4, 6, 8]
oddNumbers -> [1, 3, 5, 7]

 

 

 

 

Previous                                                    Next                                                    Home