www.kbkt.net > python 创建字典

python 创建字典

class dic(dict): pass

python---创建字典的方式 1、用{}创建字典 代码: x = {"a":"1", "b":"2"} print x 输出: {'a': '1', 'b': '2'} 2、用内置函数dict() (1)、入参为类似a="1"的键值对 代码: x = dict(a="1", b="2") print x 输出: {'a': '1', 'b': '2'} (2)、...

分别输入key和value,key输入回车结束 dic = {}while True: key = input('Input key:') if key == '': break value = input('Input value:') dic[key] = valuefor key, value in dic.items(): print(key + ' : ' + value)

如果是有规则数据则很简单 population = dict( line.strip( ).split( ' ' ) for line in open( 'population.txt' ) )

Python的数据不需要声明, 使用的时候就定义了 1 2 mydict = {} mydict2 = {} 随用随定义, 不需要纠结这个问题

a = {'a':{'b':1},'c':2}#方法1a['a']['b'] = 2a['c']=3#方法2a.update(c=3,a={"b":2})#或a.update({"a":{"b":2},"c":3})

比如:l1=[1,2,3] l2=['baidu','google','bing'] py3.x中 dict(map(lambda x,y:[x,y], l1,l2)) {1:'baidu', 2:'google', 3:'bing'} py2.x中 dict(zip(l1,l2))

>>> a=['one','two','three']>>> b={}>>> [b.setdefault(x,y) for x,y in enumerate(a)]['one', 'two', 'three']>>> b{0: 'one', 1: 'two', 2: 'three'}>>>

看代码,serial_dict.py: # -*- encoding: gbk -*-def load_dict_from_file(filepath):_dict = {}try:with open(filepath, 'r') as dict_file:for line in dict_file:(key, value) = line.strip().split(':')_dict[key] = valueexcept IOError ...

import operator class NewDict( dict ): default = None def __init__( self ,init_dict ,default ): self.default = default for key ,value in init_dict.items( ): if isinstance( value ,dict ): init_dict[ key ] = self.__class__( value...

网站地图

All rights reserved Powered by www.kbkt.net

copyright ©right 2010-2021。
www.kbkt.net内容来自网络,如有侵犯请联系客服。zhit325@qq.com