如何创建{1:100,2:99,…,100:1}格式的字典并修正错误?
Hey there! Let’s fix this problem for you. The goal is to build a dictionary where each key from 1 to 100 maps to a value that’s exactly reversed (1→100, 2→99, ..., 100→1). Here are two clean, efficient ways to do this without the issues you ran into earlier:
Method 1: Dictionary Comprehension (Most Readable)
This is the simplest and most Pythonic approach. We’ll loop through each key from 1 to 100 and calculate the corresponding value directly:
reverse_dict = {k: 101 - k for k in range(1, 101)}
Why this works:
range(1, 101)generates all integers from 1 up to (but not including) 101, giving us keys 1 through 100.- For each key
k, the value101 - kperfectly reverses the numbering: 101-1=100, 101-2=99, and so on down to 101-100=1.
Method 2: Using zip() with Ranges
If you prefer working with paired sequences, use zip() to combine two ranges—one for keys (1-100) and one for values (100-1):
reverse_dict = dict(zip(range(1, 101), range(100, 0, -1)))
Why this works:
range(100, 0, -1)generates numbers starting at 100 and counting down by 1 until it reaches 1 (the stop value 0 is excluded).zip()pairs each element from the key range with the corresponding element from the value range. Converting this zipped object to a dictionary gives exactly the structure you need.
Why Your Previous Approach Had Issues
You mentioned converting the dictionary to a list and losing key-value structure, or trying .reverse() which doesn’t work on dicts. While you could reverse a list of key-value pairs (like dict(reversed(list({k:k for k in range(1,101)}.items())))), that’s unnecessary and less efficient than building the dict correctly from the start. The methods above avoid those pitfalls entirely.
Let me know if you need any further clarification!
内容的提问来源于stack exchange,提问作者rippleEffect

