python之字典的习题(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/gardenpalace/article/details/84104931
​
#10编写一个Python程序来汇总字典中的所有条目
my = {'date':100,'dare':200,'dace':-34}
print(sum(my.values()))

#9编写一个Python程序,使用for循环遍历字典
my = {'date':100,'dare':200,'dace':-34}
for my_key, value in my.items():
    print(my_key,my[my_key])
#8编写一个Python脚本合并两个Python字典
d1 = {'a': 100, 'b': 200}
d2 = {'x': 300, 'y': 200}

d = d1.copy()
d.update(d2)
print(d)

#7编写一个Python脚本来打印一个字典,其中键是1到15之间的数字(都包括在内),值是键的平方。
d = dict()
for x in range(1,16):
    d[x]=x**2
print(d)

#6编写一个Python脚本来生成并打印一个字典,字典的形式为(x, x*x),其中包含一个数字(1到n之间)。
n=int(input("Input a number "))
d = dict()

for x in range(1,n+1):
    d[x]=x*x

print(d)

#5 = 9

d = {'x': 10, 'y': 20, 'z': 30} 
for d_key, d_value in d.items():
    print(d_key,d_value)
#4编写一个Python脚本,检查给定键是否已经存在于字典中
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def is_key_present(x):
  if x in d:
      print('Key is present in the dictionary')
  else:
      print('Key is not present in the dictionary')
is_key_present(5)
is_key_present(9)
#3编写一个Python脚本,连接后面的字典以创建一个新的字典
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1,dic2,dic3):
    dic4.update(d)
print(dic4)

#2编写一个Python脚本,向字典添加一个键
d = {0:10, 1:20}
print(d)
d.update({2:30})
print(d)

​
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
 RESTART: C:/Users/Administrator/AppData/Local/Programs/Python/Python37-32/1.py 
266
date 100
dare 200
dace -34
{'a': 100, 'b': 200, 'x': 300, 'y': 200}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
Input a number 3
{1: 1, 2: 4, 3: 9}
x 10
y 20
z 30
Key is present in the dictionary
Key is not present in the dictionary
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
{0: 10, 1: 20}
{0: 10, 1: 20, 2: 30}
>>> 

打印结果

猜你喜欢

转载自blog.csdn.net/gardenpalace/article/details/84104931
今日推荐