如何掌握使用字典

一、字典的含义

        Python 中的字典本质上是包含各种带有唯一标识符的成对信息的列表。和列表一样,字
典也广泛应用于各种商业分析。在商业分析中,可以用字典表示客户(以客户编码为键
值),也可以用字典表示产品(以序列号或产品编号为键值),还可以用字典表示资产、
销售量等。

二、区别列表和字典

      在 Python 中,这样的数据结构称为字典,在其他编程语言中则称为 关联数组 - 值存储
散列值 。在商业分析中,列表和字典都是非常重要的数据结构,但是它们之间还存在着
重要的区别,要想有效地使用字典,必须清楚这些区别。
在列表中,你可以使用被称为 索引 索引值 的连续整数来引用某个列表值。在字典中,
要引用一个字典值,则可以使用整数、字符串或其他 Python 对象,这些统称为 字典键
在唯一键值比连续整数更能反映出变量值含义的情况下,这个特点使字典比列表更实用。
在列表中,列表值是隐式排序的,因为索引是连续整数。在字典中,字典值则没有排序,
因为索引不仅仅只是数值。你可以为字典中的项目定义排序操作,但是字典确实没有内
置排序。
在列表中,为一个不存在的位置(索引)赋值是非法的。在字典中,则可以在必要的时
候创建新的位置(键)。
因为没有排序,所以当你进行搜索或添加新值时,字典的响应时间更快(当你插入一个
新项目时,计算机不需要重新分配索引值)。当处理的数据越来越多时,这是一个重要
的考虑因素。


  

三、 创建字典

1.使用花括号创建字典

2.用冒号分隔键-值对

3.用len()计算出字典中键-值对的数量

empty_dict = { }
a_dict = {'one':1, 'two':2, 'three':3}
print("Output 102: {}".format(a_dict))
print("Output 103: a_dict has {!s} elements".format(len(a_dict)))
another_dict = {'x':'printer', 'y':5, 'z':['star', 'circle', 9]}
print("Output 104: {}".format(another_dict))
print("Output 105: another_dict also has {!s} elements"\
.format(len(another_dict)))

运行结果如下:

                   

empty_dict = { }
a_dict = {'one':1, 'two':2, 'three':3}
print ("Output 102: {}".format(a_dict))
print ("Output 103: a_dict has {!s} elements".format(len(a_dict)))
another_dict = {'x':'printer', 'y':5, 'z':['star', 'circle', 9]}
print ("Output 104: {}".format(another_dict))
print ("Output 105: another_dict also has {!s} elements"\
.format(len(another_dict)))

 四、使用字典

1. 引用字典中的值

使用键来引用字典中特定的值

print("Output 106: {}".format(a_dict['two']))
print("Output 107: {}".format(another_dict['z']))

运行结果如下:                     

Output 106: 2
Output 107: ['star', 'circle', 9]
       要引用字典中一个特定的值,需要使用字典名称、一对方括号和一个特定的键值(一个字
符串)。在这个示例中, a_dict['two'] 的结果是整数 2 another_dict['z'] 的结果是列表
['star', 'circle', 9]

2. 复制

使用copy()复制一个字典

a_new_dict = a_dict.copy()
print("Output 108: {}".format(a_new_dict))

 运行结果如下:

Output 108: {'one': 1, 'two': 2, 'three': 3}

       要复制一个字典,先在字典名称后面加上 copy 函数,然后将这个表达式赋给一个新的字典
即可。在这个示例中, a_new_dict 是字典 a_dict 的一个副本。

3. 值和项目

 (1)使用keys()values()items()

(2)分别引用字典中的键、值和键-值对

print("Output 109: {}".format(a_dict.keys()))
a_dict_keys = a_dict.keys()
print("Output 110: {}".format(a_dict_keys))
print("Output 111: {}".format(a_dict.values()))
print("Output 112: {}".format(a_dict.items()))

运行结果如下:

       要引用字典的键值,在字典名称后面加上 keys 函数即可。这个表达式的结果是包含字典键
值的一个列表。要引用字典值,在字典名称后面加上 values 函数即可。这个表达式的结果
是包含字典值的一个列表。
       要想同时引用字典的键和值,在字典名称后面加上 items 函数即可。结果是一个列表,其
中包含的是键 - 值对形式的元组。例如, a_dict.items() 的结果是 [('three', 3), ('two',
2), ('one', 1)] 。在 1.4.8 节中会介绍如何使用 for 循环来对字典中的所有键和值进行解
包和引用。
if 'y' in another_dict:
 print("Output 114: y is a key in another_dict: {}."\
.format(another_dict.keys()))
if 'c' not in another_dict:
 print("Output 115: c is not a key in another_dict: {}."\
.format(another_dict.keys()))
print("Output 116: {!s}".format(a_dict.get('three')))
print("Output 117: {!s}".format(a_dict.get('four')))
print("Output 118: {!s}".format(a_dict.get('four', 'Not in dict')))
运行结果如下:
Output 114: y is a key in another_dict: dict_keys(['x', 'y', 'z']).
Output 115: c is not a key in another_dict: dict_keys(['x', 'y', 'z']).
Output 116: 3
Output 117: None
Output 118: Not in dict
        第一种方法是使用 if 语句、 in 或 not in 以及字典名称。使用 in if 语句来测试 y 是否是 another_dict 中的一个键值。
        如果语句结果为真(也就是说如果 y another_dict 中的一个键值),那么就执行 print
句;否则,就不执行。这种 if in if not in 语句经常用于测试是否存在某个键值,和其
他语句一起使用时,还可以为字典添加新的键值。

 5. 排序

print("Output 119: {}".format(a_dict))
dict_copy = a_dict.copy()
ordered_dict1 = sorted(dict_copy.items(), key=lambda item: item)
print("Output 120 (order by keys): {}".format(ordered_dict1))
ordered_dict2 = sorted(dict_copy.items(), key=lambda item: item[1])
print("Output 121 (order by values): {}".format(ordered_dict2))
ordered_dict3 = sorted(dict_copy.items(), key=lambda x: x[1], reverse=True)
print("Output 122 (order by values, descending): {}".format(ordered_dict3))
ordered_dict4 = sorted(dict_copy.items(), key=lambda x: x[1], reverse=False)
print("Output 123 (order by values, ascending): {}".format(ordered_dict4))

 运行结果如下:                    

Output 119: {'one': 1, 'two': 2, 'three': 3}
Output 120 (order by keys): [('one', 1), ('three', 3), ('two', 2)]
Output 121 (order by values): [('one', 1), ('two', 2), ('three', 3)]
Output 122 (order by values, descending): [('three', 3), ('two', 2), ('one', 1)]
Output 123 (order by values, ascending): [('one', 1), ('two', 2), ('three', 3)]
这个代码中使用了 copy 函数来为字典 a_dict 制作一个副本,副本的名称为 dict_copy 。为
字典制作副本确保了原字典 a_dict 不会被修改。下一行代码中包含了 sorted 函数、一个
items 函数生成的元组列表和一个作为 sorted 函数关键字的 lambda 函数。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值