Python中如何输出字典内同索引的两个列表对应元素
Hey there! I've got you covered. Your goal is to match up elements from the two lists in your dictionary by their index, and print them in the format you specified. Here are two straightforward ways to do this:
Method 1: Use zip() (Most Concise)
Python's built-in zip() function is perfect for this scenario—it pairs up elements from multiple iterables (like your two lists) one by one. Here's how to use it:
stocks = {"product":["iphone", "xiaomi", "samsung"], "amount":[10, 21, 17]} # Iterate over paired elements from both lists for product, amount in zip(stocks["product"], stocks["amount"]): print(f"Product name: {product}, amount: {amount}")
What this does:
zip(stocks["product"], stocks["amount"])creates tuples like("iphone", 10),("xiaomi", 21), etc., matching elements by their index.- The loop unpacks each tuple into
productandamountvariables, which we then plug into an f-string to get your desired output format.
Method 2: Index-Based Loop
If you ever need to work with the actual index number (e.g., to track which position a product is in), you can loop using indices instead:
stocks = {"product":["iphone", "xiaomi", "samsung"], "amount":[10, 21, 17]} # Extract the lists for easier access products = stocks["product"] amounts = stocks["amount"] # Loop through each index for i in range(len(products)): print(f"Product name: {products[i]}, amount: {amounts[i]}")
Quick heads-up:
Make sure both lists in your dictionary are the same length! If one is shorter than the other, zip() will stop at the end of the shorter list, and the index-based loop might throw an error if you try to access an index that doesn't exist in the shorter list.
内容的提问来源于stack exchange,提问作者Gharis Primada Hariyono

