Python 程序创建键和值为其平方的字典

编写一个 Python 程序,创建一个键和值为其平方的字典,并附带一个实际示例。

Python 程序创建键和值为其平方的字典示例

在此 Python 程序中,我们使用 for 循环迭代从 1 到用户指定的值。在 Python for 循环中,我们使用指数运算符字典赋值。

# Python Program to Create Dictionary of keys and values are square of keys

number = int(input("Please enter the Maximum Number : "))
myDict = {}

for x in range(1, number + 1):
    myDict[x] = x ** 2
    
print("\nDictionary = ", myDict)
Python Program to Create Dictionary of keys and values are square of keys

在此Python示例中,number = 5。

第一次迭代 x 将是 1:for 1 in range(1, 6)
myDict[x] = x ** 2
myDict[x] = 1 ** 2 = 1

第二次迭代 x 将是 2:for 2 in range(1, 6)
myDict[x] = 2 ** 2 = 2

对其余的for 循环迭代执行相同的操作

创建键从 1 到 n,值为其平方的字典的程序 示例 2

Python 代码用于创建键和值为其平方的字典是另一种方法。

# Python Program to Create Dictionary of keys and values are square of keys

number = int(input("Please enter the Maximum Number : "))

myDict = {x:x ** 2 for x in range(1, number + 1)}
    
print("\nDictionary = ", myDict)

键和其平方作为值的字典的输出

Please enter the Maximum Number : 6

Dictionary =  {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36}
>>> 
Please enter the Maximum Number : 9

Dictionary =  {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>>