person ={'name':'xiaobai','age':18}print ("The value of key 'name' is : ",person['name'])print ("The value of key 'city' is : ",person['city'])Out: The value of key 'name'is: xiaobaiTraceback (most recent call last): File "C:\Users\E560\Desktop\test.py", line 17,in<module>print ("The value of key 'city' is : ",person['city'])KeyError:'city'
用defaultdict再试试:
from collections import defaultdictperson =defaultdict(lambda : 'Key Not found')# 初始默认所有key对应的value均为‘Key Not Found’person['name']='xiaobai'person['age']=18print ("The value of key 'name' is : ",person['name'])print ("The value of key 'adress' is : ",person['city'])Out:The value of key 'name'is: xiaobai The value of key 'adress'is: Key Not found
from collections import defaultdictd =defaultdict(list)d['person'].append("xiaobai")d['city'].append("paris")d['person'].append("student")for i in d.items():print(i)Out: ('person', ['xiaobai','student']) ('city', ['paris'])
# create hash id for a namedtuplecols =['a','b','c']fields =" ".join(cols)+'hash_id'Data =namedtuple('Data',fields,defaults=""*len(fields))raw_result = []withopen('xx.csv',encoding='utf-8')as file: file_iter =iter(file) _ =next(file_iter)# Jump first linefor line in file_iter: each_line = line.strip('\n').split(';')+[''] raw_result.append(Data(*each_line))defcreate_hash_id(each): text ="".join(x.replace(" ","") for x in each.asdict().values()return each._replace(hash_id=hashlib.sha256(text.encode('utf-8')).hexdigest())# A list of tuples a = [Data(...),Data(...)]new_a =list(map(create_hash_id,a))# Get values for a namedtuplea[0]._asdict().values()# Get fields for a namedtuplea[0]._fields# Turn the result to dataframedf = pd.Dataframe(a,columns=Data._fields)
Data Classes can be thought of as “mutable namedtuples with defaults.” (Source) However, it’d be more accurate to say that data classes are like mutable named tuples with type hints. The “defaults” part isn’t a difference at all because named tuples can also have default values for their fields. So, at first glance, the main differences are mutability and type hints.
from collections import namedtuplefrom datetime import dateBasePerson =namedtuple("BasePerson","name birthdate country", defaults=["Canada"])classPerson(BasePerson):"""A namedtuple subclass to hold a person's data."""__slots__= ()def__repr__(self):returnf"Name: {self.name}, age: {self.age} years old."@propertydefage(self):return (date.today()- self.birthdate).days //365print(Person.__doc__)jane =Person("Jane", date(1996, 3, 5))jane.ageA namedtuple subclass to hold a person's data.25
from collections import OrderedDictprint("Before deleting:\n")od =OrderedDict()od['a']=1od['b']=2od['c']=3od['d']=4for key, value in od.items():print(key, value)print("\nAfter deleting:\n")od.pop('c')for key, value in od.items():print(key, value)print("\nAfter re-inserting:\n")od['c']=3for key, value in od.items():print(key, value)Out:Before deleting: ('a',1) ('b',2) ('c',3) ('d',4) After deleting: ('a',1) ('b',2) ('d',4) After re-inserting: ('a',1) ('b',2) ('d',4) ('c',3)
Chainmap
from collections import ChainMapcmd_proxy ={}# The user doesn't provide a proxylocal_proxy ={"proxy":"proxy.local.com"}global_proxy ={"proxy":"proxy.global.com"}config =ChainMap(cmd_proxy, local_proxy, global_proxy)config.maps=>[{},{'proxy':'proxy.local.com'},{'proxy':'proxy.global.com'}]
ChainMap 提供 .new_child() 和 a .parents property属性:
from collections import ChainMapdad ={"name":"John","age":35}mom ={"name":"Jane","age":31}family =ChainMap(mom, dad)family=>ChainMap({'name': 'Jane', 'age': 31}, {'name': 'John', 'age': 35})son ={"name":"Mike","age":0}family = family.new_child(son)for person in family.maps:print(person){'name':'Mike','age':0}{'name':'Jane','age':31}{'name':'John','age':35}family.parentsOut[11]:ChainMap({'name': 'Jane', 'age': 31}, {'name': 'John', 'age': 35})