杰瑞科技汇

Python中string和dict如何高效转换?

Of course! In Python, strings and dictionaries are two of the most fundamental and powerful data types. They are often used together. Let's break them down individually and then explore how they interact.

Python中string和dict如何高效转换?-图1
(图片来源网络,侵删)

Python Strings (str)

A string is a sequence of characters. In Python, strings are immutable, meaning they cannot be changed after they are created.

Creating Strings

You can create strings using single quotes (), double quotes (), or triple quotes ( or ).

# Single quotes
name = 'Alice'
# Double quotes (useful if the string contains single quotes)
message = "Hello, it's a nice day!"
# Triple quotes (for multi-line strings)
description = """This is a long
description that spans
multiple lines."""

Common String Operations

Operation Description Example
Concatenation Joining two or more strings. first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
Multiplication Repeating a string. s = "ha"
laugh = s * 3 # Results in "hahaha"
Slicing [start:stop:step] Extracting a substring. s = "Python"
s[1:4] # Results in "yth"
s[::2] # Results in "Pto" (every 2nd character)
Length len() Getting the number of characters. len("hello") returns 5
Methods Strings have many built-in methods. s.upper() -> "PYTHON"
s.lower() -> "python"
s.strip() -> " text " becomes "text"
s.replace("P", "J") -> "Jython"
s.split("t") -> ['Py', 'hon']

Python Dictionaries (dict)

A dictionary is a collection of key-value pairs. It's an unordered (in Python versions < 3.7), mutable data structure. You use a key to access its corresponding value. Think of it like a real dictionary: you look up a word (the key) to find its definition (the value).

Creating Dictionaries

You create dictionaries using curly braces with key: value pairs separated by commas.

Python中string和dict如何高效转换?-图2
(图片来源网络,侵删)
# A simple dictionary
student = {
    "name": "Bob",
    "age": 21,
    "major": "Computer Science"
}
# Using the dict() constructor
another_student = dict(name="Charlie", age=22, major="Math")
  • Keys: Must be unique and immutable (e.g., strings, numbers, tuples).
  • Values: Can be any data type, including other dictionaries (nested dictionaries).

Common Dictionary Operations

Operation Description Example
Accessing Values Use square brackets []. student["name"] returns "Bob"
.get() Method Safer way to access values. Returns None or a default if the key doesn't exist. student.get("major") returns "Computer Science"
student.get("gpa", 0.0) returns 0 (since "gpa" doesn't exist)
Adding/Updating Assign a value to a key. If the key exists, its value is updated. If not, it's added. student["year"] = 3 (Adds a new key)
student["age"] = 22 (Updates an existing key)
.update() Method Merges another dictionary into the current one. student.update({"gpa": 3.8, "year": 3})
Deleting Use del statement or .pop() method. del student["age"] (Deletes the key-value pair)
student.pop("major") (Deletes and returns the value)
Looping Iterate through keys, values, or items. for key in student:
    print(key)

for value in student.values():
    print(value)

for key, value in student.items():
    print(f"{key}: {value}")
Length len() Gets the number of key-value pairs. len(student) returns 3

The Powerful Combination: Strings and Dictionaries

This is where the real power lies. You often use strings as keys in dictionaries, and you frequently need to convert between string representations and dictionaries.

A) Using Strings as Dictionary Keys

This is the most common use case. Strings are perfect keys because they are descriptive and immutable.

# A dictionary to store user settings
user_settings = {
    "theme": "dark",
    "notifications": True,
    "font_size": 14
}
# Access a setting using a string key
print(user_settings["theme"])  # Output: dark
# Update a setting
user_settings["theme"] = "light"
print(user_settings["theme"])  # Output: light

B) Parsing Strings into Dictionaries

You often get data as a string (e.g., from a JSON API or a configuration file) and need to convert it into a dictionary.

Using json Module (for JSON format)

Python中string和dict如何高效转换?-图3
(图片来源网络,侵删)

JSON (JavaScript Object Notation) is a standard format for data exchange and looks almost identical to a Python dictionary.

import json
# A string in JSON format
json_string = '{"name": "David", "scores": [85, 92, 78], "active": true}'
# Convert the JSON string to a Python dictionary
data_dict = json.loads(json_string)
print(data_dict)
# Output: {'name': 'David', 'scores': [85, 92, 78], 'active': True}
# Now you can use it like a normal dictionary
print(data_dict["name"])       # Output: David
print(data_dict["scores"][1])  # Output: 92

Using ast Module (for Literal Strings)

If you have a string that looks exactly like Python dictionary syntax, you can use ast.literal_eval().

import ast
# A string that looks like a dictionary literal
dict_string = "{'city': 'London', 'country': 'UK', 'population': 8900000}"
# Safely evaluate the string to a dictionary
data_dict = ast.literal_eval(dict_string)
print(data_dict)
# Output: {'city': 'London', 'country': 'UK', 'population': 8900000}

Warning: eval() is dangerous and can execute arbitrary code. Always use ast.literal_eval() for this purpose as it only evaluates literals (strings, numbers, lists, dicts, tuples, booleans, and None).

C) Converting Dictionaries to Strings

The reverse operation is also very common, especially for sending data over a network or saving it to a file.

Using json Module (to get a JSON string)

import json
my_dict = {"user": "Eve", "id": 123, "status": "online"}
# Convert the dictionary to a JSON formatted string
json_string = json.dumps(my_dict, indent=4) # indent=4 for pretty printing
print(json_string)
# Output:
# {
#     "user": "Eve",
#     "id": 123,
#     "status": "online"
# }

Using str() (for a simple representation)

This gives you the standard Python representation of the dictionary, which is useful for debugging.

my_dict = {"user": "Eve", "id": 123}
simple_string = str(my_dict)
print(simple_string)
# Output: {'user': 'Eve', 'id': 123}

D) Formatting Strings with Dictionary Data (f-strings)

Modern Python (3.6+) uses f-strings, which are an excellent way to embed dictionary values directly into a string.

person = {
    "first_name": "Frank",
    "last_name": "Miller",
    "job_title": "Data Scientist"
}
# Using f-strings to format a string
# The 'f' before the quote enables the feature
output_string = f"Hello, my name is {person['first_name']} {person['last_name']}, and I am a {person['job_title']}."
print(output_string)
# Output: Hello, my name is Frank Miller, and I am a Data Scientist.

Summary

Concept Key Idea Example
String An immutable sequence of characters. s = "hello"
Dictionary A mutable collection of key-value pairs. d = {"key": "value"}
Interaction 1 Strings are often used as dictionary keys. config["timeout"] = 30
Interaction 2 Parse string data (like JSON) into a dictionary. data = json.loads(json_str)
Interaction 3 Convert a dictionary into a string for storage/transmission. json_str = json.dumps(my_dict)
Interaction 4 Insert dictionary values into a string. f"Value is {my_dict['key']}"
分享:
扫描分享到社交APP
上一篇
下一篇