如何将两个列表转为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 entirevaluelist to each key instead of the corresponding individual element. To make that approach work, you'd need to loop through both lists together (like withzip), assigning one pair at a time. - The
fromkeys()method creates a dictionary where all keys map to the same value. Sodict.fromkeys(year, value)would set every year to point to the entirevaluelist, 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

