字典操作
- 1.字典a={“x”:1,“z”:3},b={“y”:2,“z”:4},请设计一个函My_Func(),
当My_Func(a,b)时输出c={“x”:1,“y”:2,“z”:3},
当My_Func(b,a)时输出c={“x”:1,“y”:2,“z”:4}
答案:
def My_Func(a, b):
c = a
for i in b.keys():
if i not in c:
c[i] = b[i]
return sorted(c.items(), key=lambda x: x[1])
输出结果为:
[('x', 1), ('y', 2), ('z', 3)]
[('x', 1), ('y', 2), ('z', 4)]
- 2.有一个字典列表如下:
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
name代表品牌名,shares代表分享数量,price代表价格
问题:请编写一个程序,输出价格最高的的前三个商品,
如:
[{'name': 'AAPL', 'price': 543.22, 'shares': 50},
{'name': 'ACME', 'price': 115.65, 'shares': 75},
{'name': 'IBM', 'price': 91.1, 'shares': 100}
]
答案如下:
def max_price(li):
li.sort(key=lambda x: x['price'],reverse=True)
li_max = []
for x in range(3):
li_max.append(li[x])
return li_max
portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
print(max_price(portfolio))
输出结果为:
[{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'ACME', 'shares': 75, 'price': 115.65},
{'name': 'IBM', 'shares': 100, 'price': 91.1}]
手动换行的