Python中如何将字典键值对转为字符串并生成指定列表?
Yes, absolutely!
You can easily convert the key-value pairs of your dictionary into the desired list using a list comprehension in Python—it’s concise and readable. Here’s how:
# Your original dictionary name_dict = {"John": "Doe", "Jane": "Smith", "Jack": "Poland"} # Convert to the target list full_names = [f"{first} {last}" for first, last in name_dict.items()] print(full_names) # Output: ["John Doe", "Jane Smith", "Jack Poland"]
Breakdown of the code:
name_dict.items()iterates over each key-value pair in the dictionary, returning tuples like("John", "Doe")- The f-string
f"{first} {last}"combines the key (first name) and value (last name) with a space in between - The list comprehension wraps this logic to collect all the combined strings into a new list
If you prefer a more explicit (though less concise) approach, you could use a standard for loop instead:
full_names = [] for first, last in name_dict.items(): full_names.append(f"{first} {last}")
Either method will give you exactly the list you’re looking for.
内容的提问来源于stack exchange,提问作者MHA
相关产品推荐
相关产品推荐

