python教程48-「Python字典」知识点分享

1、字典是否是无序的

a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
a_dict

输出:
{'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}

2、键值互换

a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
new_dict = {}
for key, value in a_dict.items():
 new_dict[value] = key
new_dict

输出:
{1: 'one', 2: 'two', 3: 'thee', 4: 'four'}

3、依据某种条件,过滤字典

a_dict = {'one': 1, 'two': 2, 'thee': 3, 'four': 4}
new_dict = {}  # Create a new empty dictionary
for key, value in a_dict.items():
    if value <= 2:
       new_dict[key] = value
new_dict

输出:
{'one': 1, 'two': 2}

4、利用字典中的值,做一些计算

incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
total_income = 0.00
for value in incomes.values():
    total_income += value  # Accumulate the values in total_income
total_income

输出:
14100.0

5、字典推导式:假设您有两个数据列表,您需要根据它们创建一个新字典

objects = ['blue', 'apple', 'dog']
categories = ['color', 'fruit', 'pet']
a_dict = {key: value for key, value in zip(categories, objects)}
a_dict

输出:
{'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}

6、字典排序

incomes = {'apple': 5600.00, 'orange': 3500.00, 'banana': 5000.00}
sorted_income = {k: incomes[k] for k in sorted(incomes)}
sorted_income

输出:
{'apple': 5600.0, 'banana': 5000.0, 'orange': 3500.0}

7、内置函数,与字典配合使用 map()函数有一个包含一堆产品价格的字典,并且您需要对它们应用折扣

prices = {'apple': 0.40, 'orange': 0.35, 'banana': 0.25}
def discount(current_price):
     return (current_price[0], round(current_price[1] * 0.95, 2))
new_prices = dict(map(discount, prices.items()))
new_prices

输出:
{'apple': 0.38, 'orange': 0.33, 'banana': 0.24}

8、filter()函数 假设您想知道单价低于0.40的产品

prices = {'apple': 0.40, 'orange': 0.35, 'banana': 0.25}
def has_low_price(price):
    return prices[price] < 0.4
low_price = list(filter(has_low_price, prices.keys()))
low_price

输出:
['orange', 'banana']

9、字典解包运算符

vegetable_prices = {'pepper': 0.20, 'onion': 0.55}
fruit_prices = {'apple': 0.40, 'orange': 0.35, 'pepper': .25}
{**vegetable_prices, **fruit_prices}

输出:
{'pepper': 0.25, 'onion': 0.55, 'apple': 0.4, 'orange': 0.35}

文章来源:快学python微信公共账号
内容做了改编

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值