Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Dictionaries in Python

Dictionaries in Python

? Dictionaries in Python

A dictionary in Python is an unordered collection of items. It stores data in key-value pairs, where each key is unique and maps to a specific value. Dictionaries are highly useful for cases where you want to look up values quickly using a key.


? Creating a Dictionary

You can create a dictionary using curly braces {}, with keys and values separated by a colon :.

Example:

# Creating a dictionarymy_dict = {    "name": "John",    "age": 30,    "city": "New York"}print(my_dict)

? Output:

{'name': 'John', 'age': 30, 'city': 'New York'}

? Accessing Dictionary Elements

You can access dictionary elements by referring to their key inside square brackets [].

Example:

# Accessing values using keysprint(my_dict["name"])  # Output: Johnprint(my_dict["age"])   # Output: 30

If the key does not exist, it will raise a KeyError. To avoid this, you can use the get() method.

Example (using get()):

# Using get() to avoid KeyErrorprint(my_dict.get("name"))  # Output: Johnprint(my_dict.get("salary", "Not Available"))  # Output: Not Available

? Adding and Updating Items

You can add a new key-value pair or update the value of an existing key.

Example:

# Adding a new key-value pairmy_dict["job"] = "Engineer"# Updating an existing valuemy_dict["age"] = 31print(my_dict)

? Output:

{'name': 'John', 'age': 31, 'city': 'New York', 'job': 'Engineer'}

? Removing Items

There are several ways to remove items from a dictionary:

  1. Using del: Deletes a specific key-value pair.

  2. Using pop(): Removes a key and returns its value.

  3. Using popitem(): Removes the last key-value pair (in Python 3.7+).

  4. Using clear(): Removes all items from the dictionary.

Example:

# Using del to remove a key-value pairdel my_dict["job"]# Using pop() to remove a key-value pair and get the valueremoved_value = my_dict.pop("city")# Using popitem() to remove the last itemlast_item = my_dict.popitem()# Using clear() to remove all itemsmy_dict.clear()print(my_dict)  # Output: {}

? Looping Through a Dictionary

You can loop through a dictionary to access keys, values, or both.

1?? Looping Through Keys

# Looping through keysfor key in my_dict:    print(key)

2?? Looping Through Values

# Looping through valuesfor value in my_dict.values():    print(value)

3?? Looping Through Keys and Values

# Looping through keys and valuesfor key, value in my_dict.items():    print(f"Key: {key}, Value: {value}")

? Nested Dictionaries

Dictionaries can also contain other dictionaries as values. This is called a nested dictionary.

Example:

# Nested dictionarymy_dict = {    "person1": {"name": "John", "age": 30},    "person2": {"name": "Jane", "age": 25}}# Accessing values in nested dictionariesprint(my_dict["person1"]["name"])  # Output: John

? Dictionary Comprehensions

Just like list comprehensions, you can create dictionaries in a more concise way using dictionary comprehensions.

Example:

# Dictionary comprehension to create a square dictionarysquares = {x: x**2 for x in range(1, 6)}print(squares)

? Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

? Important Dictionary Methods

Here are some commonly used dictionary methods:

  • items(): Returns a view object that displays a list of a dictionary's key-value tuple pairs.

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

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

  • update(): Updates the dictionary with the key-value pairs from another dictionary or iterable.

  • setdefault(): Returns the value of a key if it exists, else inserts the key with a default value.

Example:

# Using update() to merge two dictionariesdict1 = {"name": "John", "age": 30}dict2 = {"city": "New York", "job": "Engineer"}dict1.update(dict2)print(dict1)  # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Engineer'}# Using setdefault() to return a default value if key doesn't existprint(my_dict.setdefault("salary", 50000))  # Output: 50000

? Summary

  • Dictionaries store data in key-value pairs.

  • You can create a dictionary using curly braces {}, access elements with square brackets [], and use methods like get(), pop(), and update().

  • You can remove elements using del, pop(), or clear().

  • You can loop through dictionaries to access keys, values, or both.

  • Nested dictionaries allow you to store dictionaries inside other dictionaries.

  • Use dictionary comprehensions to create dictionaries concisely.

Let me know if you need further examples or explanations! ?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql