In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces the relevant knowledge of Python dictionary case analysis, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this Python dictionary case analysis article. Let's take a look at it.
What is a dictionary in Python?
The dictionary in Python allows us to store a series of mappings between two sets of values, namely keys and values.
All items in the dictionary are contained in a pair of curly braces {}.
Each item in the dictionary is a mapping between a key and a value-called a key-value pair.
Key-value pairs are often called dictionary entries.
You can access these values using the appropriate keys.
This is a general example of a dictionary:
My_dict = {"key1":, "key2":, "key3":, "key4":}
In the above example
The dictionary my_dict contains four key-value pairs (items).
"key1" through "key4" is 4 keys.
You can use my_dict ["key1"] to access, my_dict ["key2"] to access, and so on.
Now that we know what a Python dictionary is, let's continue to learn dictionary understanding.
How to use dictionaries to understand how to create Python dictionaries from iterable objects
In this section, let's use dictionary understanding to create Python dictionaries from iterable objects such as lists or tuples.
If we choose to generate keys or values dynamically, we can use only one iterable object to create a new Python dictionary.
When we choose to generate values dynamically, we can use the items in the iteration as keys, and vice versa.
The general syntax is as follows. Note that the names between are placeholders for the actual variable names.
= {: for in}
Let's parse the above syntax.
{} indicates that we are populating the dictionary.
For each item in the iteration, we generate a key-value pair in the dictionary.
▶, it's time to give a simple example.
Python Dictionary understanding-example 1
Suppose we have a list of customers who visit our store, and we want to offer random discounts to each customer. We want the discount value to be between $1 and $100.
In Python, random.randint (iQuery j) returns a random integer j between I and, where both endpoints are included.
Therefore, we can use the functions in the random module of randint () Python to generate discounts between $1 and $100 for each customer in the list.
The following code snippet shows how discount_dict creates a new dictionary from the customer list.
Import randomcustomers = ["Alex", "Bob", "Carol", "Dave", "Flow", "Katie", "Nate"] discount_dict = {customer:random.randint (1100) for customer in customers} print (discount_dict) # Output {'Alex': 16,' Bob': 26, 'Carol': 83,' Dave': 21, 'Flow': 38,' Katie': 47, 'Nate': 89}
The above example does the following:
Iterate through the customer list (customers)
Use the name of each customer as the key, and
Generate a random discount between $1 and $100 as the value of the key.
How to use dictionaries to understand creating Python dictionaries from two iterable objects
What if we already have predefined iterable objects that contain keys and values? Suppose you have two lists, list_1 and list_2-list_1 contains the corresponding values for the key and list_2.
We can now use Python's zip () function to compress the two lists to generate key-value pairs.
Note: this zip function takes a series of iterable objects as arguments and returns a tuple iterator, as shown in the following figure.
So, the first tuple is the first key-value pair, the second tuple is the second key-value pair, and generally speaking, the I-tuple is the I-th key-value pair.
In this case, dictionary understanding takes the following form:
= {: for (key,value) in zip (list1,list2)}
Parsing the above syntax is very simple.
Keys and values can be used as tuples because we have used the zip () function to compress them together.
Now, let's iterate through the tuple iterator to get the key-value pairs of the dictionary.
▶ it's time to look at another quick example.
Python Dictionary understanding-example 2
Suppose we want to create a dictionary of weekly temperatures in our city. The number of days should be a key, and the temperature corresponding to days (degrees Celsius) should be a value.
Suppose we have two lists of days and temperature, as shown below.
Days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] temp_C = [30.5, 32.6, 33.8, 33.4, 29.8, 29.2, 29.9]
We can now continue to use dictionary understanding to create weekly temperature dictionaries.
# Creating a dictionary of weekly tempertaures# from the list of temperatures and daysweekly_temp = {day:temp for (day,temp) in zip (days,temp_C)} print (weekly_temp) # Output {'Sunday': 30.5,' Monday': 32.6, 'Tuesday': 31.8,' Wednesday': 33.4, 'Thursday': 29.8,' Friday': 30.2, 'Saturday': 29.9}
In the above example, we use the zip () function to compress the date and temperature list together. We can now get the temperature of the day by using any day as the key to access the dictionary, as shown below:
Weekly_temp ["Thursday"] # Output29.8 how to use the items () method on Python dictionaries
So far, we have seen how to use keys to access values. How do we access all the key-value pairs in the dictionary?
To do this, we can call the method on the items () dictionary to get all the key-value pairs, as shown in the following code snippet.
Discount_dict.items () # Outputdict_items ([('Alex', 16), (' Bob', 26), ('Carol', 83), (' Dave', 21), ('Flow', 38), (' Katie', 47), ('Nate', 89)]) how to use dictionaries to understand how to create an Python dictionary from an existing dictionary
Suppose we already have a Python dictionary.
However, we want to create a new dictionary that contains only the items in our dictionary that meet certain criteria. Dictionary understanding is very convenient in this respect.
= {: for (key,value) in .items () if}
Let's parse the above syntax. We use the items () method and get all the key-value pairs in the existing dictionary.
We visit the first dictionary entry and check to see if the condition evaluation is True.
If the condition is True, we add the first item to our new dictionary.
Then we repeat these steps for all the items in the existing dictionary.
▶, let's give an example of how this works.
Python Dictionary understanding-example 3
Let's build on the discount example from the previous creation of the discount_dict dictionary. Let's discount_dict look at our dictionary again.
{'Alex': 16,' Bob': 26, 'Carol': 83,' Dave': 21, 'Flow': 38,' Katie': 47, 'Nate': 89}
We see that some customers are lucky to get higher discounts than others. Let's solve this difference and make all our customers satisfied.
We now want to offer a 10% discount on the next purchase for customers with a discount of less than $30.
In this case, we are customer_10 to create a new dictionary from our discount_dict dictionary.
Customer_10 = {customer:discount for (customer, discount) in discount_dict.items () if discount
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.