StudyLover
  • Home
  • Study Zone
  • Profiles
  • Contact us
  • Sign in
StudyLover Dictionaries
Download
  1. Python
  2. Problem Solving: Lists, Dictionaries, and Function-Based Design
Lists : Functions
Problem Solving: Lists, Dictionaries, and Function-Based Design

Dictionaries in Python

Dictionaries are unordered collections of key-value pairs. They provide a flexible way to store and retrieve data based on unique keys.

Creating Dictionaries

Python

my_dict = {"name": "Alice", "age": 30, "city": "New York"}

Accessing Values

Python

name = my_dict["name"]  # Output: "Alice"

Modifying Values

Python

my_dict["age"] = 31

Adding New Key-Value Pairs

Python

my_dict["country"] = "USA"

Deleting Key-Value Pairs

Python

del my_dict["city"]

Checking for Keys

Python

if "age" in my_dict:

  print("age key exists")

Iterating Over Dictionaries

Python

for key, value in my_dict.items():

  print(key, value)

Common Dictionary Methods

  • keys(): Returns a view of the dictionary's keys.

  • values(): Returns a view of the dictionary's values.

  • items(): Returns a view of the dictionary's key-value pairs as tuples.

  • get(key, default=None): Returns the value for a key, or a default value if the key doesn't exist.

  • pop(key, default=None): Removes a key-value pair and returns the value.

  • update(other_dict): Updates the dictionary with the contents of another dictionary.

Example

Python

person = {"name": "John", "age": 35}

person["occupation"] = "Engineer"

print(person.get("address", "Unknown"))  # Output: "Unknown"

person.pop("age")

print(person)  # Output: {'name': 'John', 'occupation': 'Engineer'}

Dictionaries are a powerful data structure in Python, allowing you to store and retrieve data efficiently based on key-value pairs.

Uses of Dictionaries in Python

Dictionaries are versatile data structures in Python with numerous applications. Here are some common use cases:

1. Storing Key-Value Pairs

  • Storing configuration settings:

Python

config = {

    "host": "example.com",

    "port": 8080,

    "username": "user"

}

  • Creating lookup tables:

Python

phonebook = {

    "Alice": "123-456-7890",

    "Bob": "987-654-3210"

}

  • Storing data from APIs or databases:

Python

data = {

    "name": "John Doe",

    "age": 30,

    "city": "New York"

}

2. Counting Occurrences

  • Counting word frequencies:

Python

text = "This is a sample text. This is another sentence."

word_count = {}

for word in text.split():

    word_count[word] = word_count.get(word, 0) + 1

print(word_count)

3. Implementing Caching

  • Storing frequently accessed data:

Python

cache = {}

def expensive_function(x):

    if x in cache:

        return cache[x]

    result = # Calculate the result

    cache[x] = result

    return result

4. Creating Graphs and Trees

  • Representing nodes and their connections:

Python

graph = {

    "A": ["B", "C"],

    "B": ["D", "E"],

    "C": ["F"]

}

5. Customizing Data Structures

  • Creating custom data types:

Python

class Person:

    def __init__(self, name, age):

        self.name = name

        self.age = age

 

people = {

    "Alice": Person("Alice", 30),

    "Bob": Person("Bob", 25)

}

These are just a few examples of how dictionaries can be used in Python. Their flexibility and efficiency make them a valuable tool for a wide range of applications.

Lists Functions
Our Products & Services
  • Home
Connect with us
  • Contact us
  • +91 82955 87844
  • Rk6yadav@gmail.com

StudyLover - About us

The Best knowledge for Best people.

Copyright © StudyLover
Powered by Odoo - Create a free website