Python Dictionaries

 


Python Dictionaries: An Overview


In Python, dictionaries are a useful data structure that allows you to store and retrieve data in key-value pairs. Dictionaries are often used in programming for tasks like storing configuration settings, caching data, and creating data models. In this blog post, we'll take a closer look at dictionaries in Python, including how to create them, access their values, and perform common operations.


Creating a Dictionary in Python


To create a dictionary in Python, you use curly braces {} and separate key-value pairs with a colon. Here's an example of a dictionary that maps string keys to integer values:


my_dict = {"apple": 5, "banana": 2, "orange": 8}

You can also create an empty dictionary using the dict() constructor:



my_dict = dict()

Accessing Values in a Dictionary


To access the value associated with a key in a dictionary, you use square brackets [] and provide the key as the index. For example, to get the value associated with the key "apple" in the dictionary above, you would use:


apple_value = my_dict["apple"]

If the key doesn't exist in the dictionary, you'll get a KeyError. To avoid this, you can use the get() method, which returns None if the key is not found:


orange_value = my_dict.get("orange")

Adding and Modifying Values in a Dictionary


To add a new key-value pair to a dictionary, you simply assign a value to a new key using square brackets:


my_dict["pear"] = 3

To modify the value associated with an existing key, you use square brackets to assign a new value to the key:


my_dict["apple"] = 10

Removing Values from a Dictionary


To remove a key-value pair from a dictionary, you use the del keyword and provide the key as the index:


del my_dict["banana"]

Iterating Over a Dictionary


To iterate over the keys and values in a dictionary, you can use the items() method, which returns a sequence of (key, value) tuples:


for key, value in my_dict.items():

    print(key, value)

This will output:


apple 10

orange 8

pear 3

Conclusion


Dictionaries are a powerful tool in Python that can help you store and manipulate data in a flexible and efficient way. With the examples and techniques we've covered in this blog post, you should be well on your way to mastering dictionaries in Python.





Here are some commonly used Python functions in dictionaries along with explanations and code samples:


dict(): This function creates a new dictionary. You can pass in an optional argument, which can be a dictionary, a sequence of key-value pairs, or keyword arguments.


# Creating a new dictionary

my_dict = dict()


# Creating a dictionary with key-value pairs

my_dict = dict({'apple': 5, 'banana': 2, 'orange': 8})


# Creating a dictionary with keyword arguments

my_dict = dict(apple=5, banana=2, orange=8)

len(): This function returns the number of key-value pairs in a dictionary.

# Getting the length of a dictionary

my_dict = {'apple': 5, 'banana': 2, 'orange': 8}

print(len(my_dict)) # Output: 3

keys(): This function returns a view object that contains the keys of a dictionary.


# Getting the keys of a dictionary

my_dict = {'apple': 5, 'banana': 2, 'orange': 8}

print(my_dict.keys()) # Output: dict_keys(['apple', 'banana', 'orange'])

values(): This function returns a view object that contains the values of a dictionary.


# Getting the values of a dictionary

my_dict = {'apple': 5, 'banana': 2, 'orange': 8}

print(my_dict.values()) # Output: dict_values([5, 2, 8])

items(): This function returns a view object that contains the key-value pairs of a dictionary as tuples.


# Getting the items of a dictionary

my_dict = {'apple': 5, 'banana': 2, 'orange': 8}

print(my_dict.items()) # Output: dict_items([('apple', 5), ('banana', 2), ('orange', 8)])

get(): This function returns the value associated with a key in a dictionary. If the key is not found, it returns None or a default value that you can provide as an argument.


# Getting the value associated with a key

my_dict = {'apple': 5, 'banana': 2, 'orange': 8}

print(my_dict.get('apple')) # Output: 5


# Getting the value associated with a non-existent key

print(my_dict.get('pear')) # Output: None


# Getting the value associated with a non-existent key with a default value

print(my_dict.get('pear', 0)) # Output: 0

pop(): This function removes the key-value pair associated with a key in a dictionary and returns the value. If the key is not found, it raises a KeyError or returns a default value that you can provide as an argument.


# Removing a key-value pair from a dictionary

my_dict = {'apple': 5, 'banana': 2, 'orange': 8}

value = my_dict.pop('apple')

print(value) # Output: 5

print(my_dict) # Output: {'banana': 2, 'orange': 8}


# Removing a non-existent key-value pair with a default value

value = my_dict.pop('pear', 0)

print(value) # Output: 0

update(): This function updates a dictionary with the key-value pairs from another dictionary, a sequence of key-value pairs, or keyword arguments.



MCQ questions on python dictionaries with correct answers



What is a dictionary in Python?

a) A list of elements

b) A collection of unordered key-value pairs

c) A collection of ordered key-value pairs

d) A collection of strings

Answer: b


How do you create an empty dictionary in Python?

a) dict()

b) {}

c) new dict

d) new {}

Answer: b


What is the function used to add a new key-value pair to a dictionary in Python?

a) add()

b) insert()

c) update()

d) append()

Answer: c


Which of the following is a valid way to access the value associated with the key 'age' in a dictionary called 'person'?

a) person[age]

b) person{'age'}

c) person('age')

d) person.get('age')

Answer: d


What is the result of calling the keys() function on a dictionary?

a) A list of the keys in the dictionary

b) A list of the values in the dictionary

c) A list of the key-value pairs in the dictionary

d) A view object of the keys in the dictionary

Answer: d


What is the result of calling the values() function on a dictionary?

a) A list of the keys in the dictionary

b) A list of the values in the dictionary

c) A list of the key-value pairs in the dictionary

d) A view object of the values in the dictionary

Answer: d


What is the result of calling the items() function on a dictionary?

a) A list of the keys in the dictionary

b) A list of the values in the dictionary

c) A list of the key-value pairs in the dictionary

d) A view object of the key-value pairs in the dictionary

Answer: d


How do you remove a key-value pair from a dictionary in Python?

a) Using the remove() method

b) Using the pop() method

c) Using the delete() method

d) Using the discard() method

Answer: b


What happens if you try to access a key that doesn't exist in a dictionary in Python?

a) A KeyError is raised

b) The dictionary returns None

c) The dictionary returns an empty string

d) The dictionary returns an empty list

Answer: a


How do you check if a key exists in a dictionary in Python?

a) Using the exists() method

b) Using the in keyword

c) Using the contains() method

d) Using the has() method

Answer: b


What is the result of calling the clear() method on a dictionary?

a) The dictionary is emptied of all key-value pairs

b) The dictionary is deleted from memory

c) The dictionary is sorted in alphabetical order

d) The dictionary is reversed in order

Answer: a


What is the difference between a dictionary and a list in Python?

a) A list contains ordered elements while a dictionary contains unordered key-value pairs

b) A list can only contain strings while a dictionary can contain any data type

c) A list can contain duplicate elements while a dictionary cannot

d) A list is mutable while a dictionary is immutable

Answer: a


How do you sort a dictionary by value in Python?

a) Using the sort() method

b) Using the sorted() function

c) Using the order_by() method

d) Using the value_sort() method

Answer: b


Here are five Python programming assignments on dictionaries:


Word Count: Write a program that takes a sentence as input and outputs a dictionary where the keys are the words in the sentence, and the values are the number of times each word appears. For example, if the input sentence is "I love python programming", the output dictionary would be {'I': 1, 'love': 1, 'python': 1, 'programming': 1}.


Phonebook: Write a program that creates a phonebook as a dictionary, where the keys are names and the values are phone numbers. The program should allow the user to add, delete, and look up phone numbers by name.


Character Frequency: Write a program that takes a string as input and outputs a dictionary where the keys are the characters in the string, and the values are the number of times each character appears. For example, if the input string is "hello", the output dictionary would be {'h': 1, 'e': 1, 'l': 2, 'o': 1}.


File Analysis: Write a program that reads a text file and outputs a dictionary where the keys are the words in the file, and the values are the number of times each word appears. You can assume that the file only contains words separated by spaces.


Frequency Distribution: Write a program that takes a list of numbers as input and outputs a dictionary where the keys are the numbers in the list, and the values are the frequency of each number. For example, if the input list is [1, 2, 3, 3, 4, 4, 4], the output dictionary would be {1: 1, 2: 1, 3: 2, 4: 3}.






Some harder questions


Unique Elements: Write a program that takes a list of elements as input and outputs a dictionary where the keys are the unique elements in the list, and the values are the number of times each unique element appears. For example, if the input list is [1, 2, 1, 3, 4, 2, 5], the output dictionary would be {1: 2, 2: 2, 3: 1, 4: 1, 5: 1}.


Inverted Index: Write a program that reads a set of text documents and creates an inverted index as a dictionary, where the keys are words and the values are lists of document IDs where the word appears. For example, if the input documents are "document1.txt" and "document2.txt" with the following contents:


document1.txt: "The quick brown fox jumps over the lazy dog"


document2.txt: "The quick brown fox jumps over the lazy cat"


the output dictionary would be {'The': ['document1.txt', 'document2.txt'], 'quick': ['document1.txt', 'document2.txt'], 'brown': ['document1.txt', 'document2.txt'], 'fox': ['document1.txt', 'document2.txt'], 'jumps': ['document1.txt', 'document2.txt'], 'over': ['document1.txt', 'document2.txt'], 'the': ['document1.txt', 'document2.txt'], 'lazy': ['document1.txt', 'document2.txt', 'document2.txt'], 'dog': ['document1.txt'], 'cat': ['document2.txt']}.


Dictionary Comprehension: Write a program that takes a dictionary of student grades as input and outputs a new dictionary where the keys are the student names and the values are the average grades. Use dictionary comprehension to create the new dictionary. For example, if the input dictionary is {'Alice': [85, 90, 92], 'Bob': [70, 80, 75], 'Charlie': [90, 85, 88]}, the output dictionary would be {'Alice': 89, 'Bob': 75, 'Charlie': 87.67}.


Zip Code Lookup: Write a program that reads a list of US cities and zip codes from a CSV file and creates a dictionary where the keys are the zip codes and the values are the corresponding city names. The program should allow the user to look up a city name by entering a zip code. The CSV file should have two columns: "city" and "zip_code".


Scrabble Score: Write a program that takes a word as input and outputs its Scrabble score as a dictionary, where the keys are the letters in the word and the values are the corresponding point values. Use dictionary comprehension to create the dictionary. For example, if the input word is "HELLO", the output dictionary would be {'H': 4, 'E': 1, 'L': 1, 'O': 1}.





Dictionary comprehension is a concise and efficient way to create a dictionary in Python. It allows you to create a dictionary using a single line of code, by specifying the key-value pairs and conditions that determine the dictionary's contents.


The basic syntax of a dictionary comprehension is:


{key:value for (key, value) in iterable if condition}

Here, the iterable can be any sequence (e.g. list, tuple, or string) or an iterable object (e.g. range or enumerate), and the condition is optional.


For example, consider the following code that uses a dictionary comprehension to create a dictionary of squares for the numbers 1 to 5:


squares = {x:x*x for x in range(1,6)}

print(squares)

Output:


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

In this example, the dictionary comprehension iterates over the range of numbers 1 to 5, and creates key-value pairs where the key is the number and the value is its square. The resulting dictionary is assigned to the variable squares and printed.


You can also use dictionary comprehension with conditional statements to filter out certain key-value pairs. For example, consider the following code that uses a dictionary comprehension to create a dictionary of even squares for the numbers 1 to 5:


even_squares = {x:x*x for x in range(1,6) if x % 2 == 0}

print(even_squares)

Output:

{2: 4, 4: 16}

In this example, the dictionary comprehension includes only the key-value pairs where the key is an even number, by using the condition if x % 2 == 0.


Dictionary comprehension is a powerful feature in Python that can simplify your code and make it more readable. However, it's important to use it judiciously and avoid creating overly complex or hard-to-read expressions.





In Python, a dictionary is a collection of key-value pairs where each key is unique and associated with a value. A pandas dataframe, on the other hand, is a two-dimensional labeled data structure with columns of potentially different types.


Here is how you can convert a dictionary to a pandas dataframe:



import pandas as pd


# Example dictionary

my_dict = {'name': ['John', 'Alice', 'Bob'],

           'age': [25, 30, 35],

           'city': ['New York', 'Paris', 'London']}


# Convert dictionary to pandas dataframe

df = pd.DataFrame(my_dict)


# View the resulting dataframe

print(df)

This will output:



    name  age      city

0   John   25  New York

1  Alice   30     Paris

2    Bob   35    London

To convert a pandas dataframe back to a dictionary, you can use the to_dict() method of the dataframe:


# Convert pandas dataframe back to dictionary

my_dict = df.to_dict()


# View the resulting dictionary

print(my_dict)

This will output:


{'name': {0: 'John', 1: 'Alice', 2: 'Bob'},

 'age': {0: 25, 1: 30, 2: 35},

 'city': {0: 'New York', 1: 'Paris', 2: 'London'}}

By default, to_dict() returns a dictionary where each column of the dataframe is a key and the values are themselves dictionaries with keys as the index labels and values as the column values for that index label. If you want to change the orientation of the resulting dictionary, you can pass the orient parameter to to_dict(). For example, df.to_dict(orient='list') will return a dictionary where each column of the dataframe is a key and the values are a list of column values.




Post a Comment

0 Comments