You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将两个列表转为Python字典的对应键值对?

Hey Carolina, let's get this dictionary sorted out for you! First, let's fix a small syntax issue in your value list: in Python, integers can't start with a leading 0 (unless you're working with octal numbers, which doesn't seem to be the case here). So 0987 will throw a SyntaxError—you'll want to change that to 987 first.

Now, here's the simplest and most efficient way to create your desired dictionary using your two lists:

Using zip() and dict()

The zip() function pairs up elements from your year and value lists (one from each list at the same index), and then we convert that paired result directly into a dictionary with dict().

year = [2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017]
# Fixed leading 0 issue with 987
value = [1, 123, 8765, 987, 182735, 3459, 9, 0, 2, 835, 874]

# Create the dictionary
year_value_dict = dict(zip(year, value))

# Test it out
print(year_value_dict[2007])  # Output: 1
print(year_value_dict[2008])  # Output: 123

Why your previous methods didn't work

  • When you tried dic[key] = value, you were probably assigning the entire value list to each key instead of the corresponding individual element. To make that approach work, you'd need to loop through both lists together (like with zip), assigning one pair at a time.
  • The fromkeys() method creates a dictionary where all keys map to the same value. So dict.fromkeys(year, value) would set every year to point to the entire value list, not the specific element you want. That's why it didn't give you the result you needed.

Alternative: Dictionary Comprehension

If you prefer a more explicit approach, you can use a dictionary comprehension to loop through the indices of your lists:

year_value_dict = {year[i]: value[i] for i in range(len(year))}

Just make sure both lists are the same length—if one is shorter than the other, zip() will stop at the end of the shorter list, and you'll lose some data.

内容的提问来源于stack exchange,提问作者Carolina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:14:33