赞
踩
____tz_zs
字典类型(dict)是“键–值”数据项的组合,每个元素是一个键值对。如:身份证号(键)–个人信息(值)。值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。
字典类型的数据是无序的,字典类型数据通过映射查找数据项。
dict1 = {'a': 1, 'b': 2}
print(dict1) # {'a': 1, 'b': 2}
dict2 = dict(a=1, b=2)
print(dict2) # {'a': 1, 'b': 2}
dict3 = dict([('a', 1), ('b', 2)])
print(dict3) # {'a': 1, 'b': 2}
asset_list = ['aa', 'bb', 'cc']
d = dict.fromkeys(asset_list, 0.) #
print(d) # {'aa': 0.0, 'bb': 0.0, 'cc': 0.0}
# 两个列表 list 组合成字典 dict d1 = {k: v for k in ['a', 'b', 'c'] for v in ['A', 'B', 'C']} # 两两组合,错误方法,因为每个键对应一个值,在循环中,值'C' 将 值"B'和'A' 替换了 print(d1) # {'a': 'C', 'c': 'C', 'b': 'C'} d2 = {k: v for k, v in [('a', 'A'), ('b', 'B'), ('c', 'C')]} print(d2) # {'a': 'A', 'b': 'B', 'c': 'C'} d3 = {k: v for k, v in zip(['a', 'b', 'c'], ['A', 'B', 'C'])} print(d3) # {'a': 'A', 'b': 'B', 'c': 'C'} # 关于zip() 函数 z = zip(['a', 'b', 'c'], ['A', 'B', 'C']) # zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象。 print(type(z)) # <class 'zip'> print(z) # <zip object at 0x000001C8505EE288> l = list(z) # list() 转换为列表 print(l) # [('a', 'A'), ('b', 'B'), ('c', 'C')] # 多层循环创建 dict print({k: {v: 1} for k in ['a', 'b', 'c'] for v in ['A', 'B', 'C']}) # 多级字典,错误方法 # {'b': {'C': 1}, 'c': {'C': 1}, 'a': {'C': 1}} print({k: {v: 1 for v in ['A', 'B', 'C']} for k in ['a', 'b', 'c']}) # 多级字典 # {'b': {'B': 1, 'C': 1, 'A': 1}, 'c': {'B': 1, 'C': 1, 'A': 1}, 'a': {'B': 1, 'C': 1, 'A': 1}}
tag_list = [{"price": "1.1", "value": "100", "signal": True},
{"price": "1.2", "value": "200", "signal": True},
{"price": "1.3", "value": "300", "signal": False}]
# 筛选字典
format_tag1 = [{k: v for k, v in d.items()} for d in tag_list if d["signal"] is True]
print(format_tag1) # [{'price': '1.1', 'value': '100', 'signal': True}, {'price': '1.2', 'value': '200', 'signal': True}]
# 修改字典中的数据
format_tag2 = [{k: float(v) for k, v in d.items()} for d in tag_list]
print(format_tag2) # [{'price': 1.1, 'value': 100.0, 'signal': 1.0}, {'price': 1.2, 'value': 200.0, 'signal': 1.0}, {'price': 1.3, 'value': 300.0, 'signal': 0.0}]
format_tag3 = [{k: float(v) if not isinstance(v, bool) else v for k, v in d.items()} for d in tag_list]
print(format_tag3) # [{'price': 1.1, 'value': 100.0, 'signal': True}, {'price': 1.2, 'value': 200.0, 'signal': True}, {'price': 1.3, 'value': 300.0, 'signal': False}]
format_tag4 = [{k if k != "signal" else k.upper(): float(v) if not isinstance(v, bool) else v for k, v in d.items()} for d in tag_list]
print(format_tag4) # [{'price': 1.1, 'value': 100.0, 'SIGNAL': True}, {'price': 1.2, 'value': 200.0, 'SIGNAL': True}, {'price': 1.3, 'value': 300.0, 'SIGNAL': False}]
#!/usr/bin/python2.7 # -*- coding:utf-8 -*- """ @author: tz_zs """ import numpy as np import pandas as pd import matplotlib.pyplot as plt list_l = [[1, 3, 3, 5, 4.], [11, 7, 15, 13, 9.1], [4, 2, 7, 9, 3.5], [15, 11, 12, 6, 11.1]] index = ["2018-07-01", "2018-07-02", "2018-07-03", "2018-07-04"] col = ['a', 'b', 'c', 'd', 'e'] df = pd.DataFrame(list_l, index=index, columns=col) print(df) """ a b c d e 2018-07-01 1 3 3 5 4.0 2018-07-02 11 7 15 13 9.1 2018-07-03 4 2 7 9 3.5 2018-07-04 15 11 12 6 11.1 """ dict_demo1 = {key_ind: [] for key_ind in index} print(dict_demo1) """ {'2018-07-02': [], '2018-07-04': [], '2018-07-01': [], '2018-07-03': []} """ dict_demo2 = {key_ind: {key_col: df.loc[key_ind, key_col] for key_col in col} for key_ind in index} print(dict_demo2) """ {'2018-07-04': {'c': 12.0, 'd': 6.0, 'b': 11.0, 'a': 15.0, 'e': 11.1}, '2018-07-03': {'c': 7.0, 'd': 9.0, 'b': 2.0, 'a': 4.0, 'e': 3.5}, '2018-07-02': {'c': 15.0, 'd': 13.0, 'b': 7.0, 'a': 11.0, 'e': 9.0999999999999996}, '2018-07-01': {'c': 3.0, 'd': 5.0, 'b': 3.0, 'a': 1.0, 'e': 4.0}} """
demo:
# !/usr/bin/python2.7 # -*- coding:utf-8 -*- """ @author: tz_zs """ keys = ['a', 'b', 'c'] mydict = {key: "value_%s" % key for key in keys} print(mydict) # {'a': 'value_a', 'c': 'value_c', 'b': 'value_b'} mydict["d"] = "dddd" print(mydict) # {'a': 'value_a', 'c': 'value_c', 'b': 'value_b', 'd': 'dddd'} # d.setdefault 如果键存在,则和get()一样获取对应值,如果键不存在于字典中,将会添加键并将值设为default print(mydict.setdefault("d", "ddddset")) # dddd print(mydict) # {'a': 'value_a', 'c': 'value_c', 'b': 'value_b', 'd': 'dddd'} print(mydict.setdefault("e", "eeeeset")) # eeeeset print(mydict) # {'a': 'value_a', 'c': 'value_c', 'b': 'value_b', 'e': 'eeeeset', 'd': 'dddd'}
# !/usr/bin/python2.7 # -*- coding:utf-8 -*- """ @author: tz_zs """ d = {"a": 1, 'b': 2, 'c': {'cc': 3, 'cc2': 4}} print(d) # {'a': 1, 'c': {'cc': 3, 'cc2': 4}, 'b': 2} d.update({"cc": 44}) print(d) # {'a': 1, 'cc': 44, 'c': {'cc': 3, 'cc2': 4}, 'b': 2} d.update({"c": {"cc": 44}}) print(d) # {'a': 1, 'cc': 44, 'c': {'cc': 44}, 'b': 2}
# !/usr/bin/python2.7 # -*- coding:utf-8 -*- """ @author: tz_zs """ keys = ['a', 'b', 'c'] mydict = {key: "value_%s" % key for key in keys} print(mydict) # {'a': 'value_a', 'c': 'value_c', 'b': 'value_b'} del mydict["b"] print(mydict) # {'a': 'value_a', 'c': 'value_c'} mydict.clear() print(mydict) # {} del mydict print(mydict) """ Traceback (most recent call last): File "/home/zmate/tzzs/mytz/test.py", line 19, in <module> print(mydict) NameError: name 'mydict' is not defined """
#!/usr/bin/python2.7 # -*- coding:utf-8 -*- """ @author: tz_zs """ keys = ['a', 'b', 'c', 'd', 'e'] mydict = {key: "value_%s" % key for key in keys} print(mydict) """ {'a': 'value_a', 'd': 'value_d', 'c': 'value_c', 'e': 'value_e', 'b': 'value_b'} """ print(mydict.get("a")) # value_a print(mydict["a"]) # value_a # print(mydict["aaa"]) # KeyError: 'aaa' print(mydict.get("aaa")) # None print(mydict.get("aaa", {})) # {} print(mydict.get("aaa", {}).get("aaa", {})) # {}
key in d
key in d.keys()
vaule in d.values()
#!/usr/bin/python2.7 # -*- coding:utf-8 -*- """ @author: tz_zs """ keys = ['a', 'b', 'c', 'd', 'e'] mydict = {key: "value_%s" % key for key in keys} print(mydict) # {'a': 'value_a', 'd': 'value_d', 'c': 'value_c', 'e': 'value_e', 'b': 'value_b'} # 查询是否在字典的key中 print("a" in mydict) # True print("a" in mydict.keys()) # True print("f" in mydict) # False print("value_a" in mydict) # False # 查询是否在字典的value中 print("value_a" in mydict.values()) # True
# 遍历所有的key:
for key in d.keys():
print(key)
# 遍历所有的value:
for value in d.values():
print(value)
# 遍历所有的键值对:
for item in d.items():
print(items) # 输出的是元组格式
# 或者
for k,v in d.items():
print(k,"----",v)
#!/usr/bin/python2.7 # -*- coding:utf-8 -*- """ @author: tz_zs """ keys = ['a', 'b', 'c', 'd', 'e'] mydict = {key: "value_%s" % key for key in keys} print(mydict) # {'a': 'value_a', 'd': 'value_d', 'c': 'value_c', 'e': 'value_e', 'b': 'value_b'} for k in mydict.keys(): print(k) """ b d e a c """ for v in mydict.values(): print(v) """ value_b value_d value_e value_a value_c """ for item in mydict.items(): print(item) """ ('b', 'value_b') ('d', 'value_d') ('e', 'value_e') ('a', 'value_a') ('c', 'value_c') """ for k, v in mydict.items(): print(k, "----", v) """ b ---- value_b d ---- value_d e ---- value_e a ---- value_a c ---- value_c """
在Python中,检查一个元素是否在 dicitonary 或 set 中存在的效率很高。因为 dict 和 set 使用哈希表来实现。查找效率可以达到 O(1)。如果需要经常检查成员,建议使用 set 或 dict 。
d.copy() 返回一个 dict 的浅复制
# -*- coding:utf-8 -*- """ @author: tz_zs """ mydict = { "china": { "shanghai": {"person1": {"age": 20, "data": [77, 87, 99]}}, } } print(mydict) # {'china': {'shanghai': {'person1': {'age': 20, 'data': [77, 87, 99]}}}} mycopy = mydict.copy() mydict["china"] = 111 print(mydict) # {'china': 111} print(mycopy) # {'china': {'shanghai': {'person1': {'age': 20, 'data': [77, 87, 99]}}}} mydict = { "china": { "shanghai": {"person1": {"age": 20, "data": [77, 87, 99]}}, } } print(mydict) # {'china': {'shanghai': {'person1': {'age': 20, 'data': [77, 87, 99]}}}} mycopy = mydict.copy() mydict["china"]["shanghai"] = 111 print(mydict) # {'china': {'shanghai': 111}} print(mycopy) # {'china': {'shanghai': 111}}
如需深层复制 dict,可使用 copy.deepcopy()
# -*- coding:utf-8 -*- """ @author: tz_zs """ import copy mydict = { "china": { "shanghai": {"person1": {"age": 20, "data": [77, 87, 99]}}, } } print(mydict) # {'china': {'shanghai': {'person1': {'age': 20, 'data': [77, 87, 99]}}}} mycopy = copy.deepcopy(mydict) mydict["china"] = 111 print(mydict) # {'china': 111} print(mycopy) # {'china': {'shanghai': {'person1': {'age': 20, 'data': [77, 87, 99]}}}} mydict = { "china": { "shanghai": {"person1": {"age": 20, "data": [77, 87, 99]}}, } } print(mydict) # {'china': {'shanghai': {'person1': {'age': 20, 'data': [77, 87, 99]}}}} mycopy = copy.deepcopy(mydict) mydict["china"]["shanghai"] = 111 print(mydict) # {'china': {'shanghai': 111}} print(mycopy) # {'china': {'shanghai': {'person1': {'age': 20, 'data': [77, 87, 99]}}}}
内置函数 cmp(x, y)
比较 x,y 两个参数,x < y 时返回值为 -1,x > y 时返回值为 1,x == y 时返回值为 0。
d1 = {"a": 2, "b": 4}
d2 = {"a": 2, "b": 5}
d3 = {"a": 2, "b": 3}
print(cmp(d1, d1)) # 0
print(cmp(d1, d2)) # -1
print(cmp(d1, d3)) # 1
https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。