zoukankan      html  css  js  c++  java
  • Python 字典

    1、一种通过名字引用值的数据结构,这种结构类型称为映射(mapping).字典是Python中唯一内建的映射类型。字典中的值没有特殊顺序,但是都是存储在一个特定的键(key)里,键可以是数字、字符串甚至是元组.字典中的键是唯一的,而值并不唯一

    2、dict函数,根本不是真正的函数,它是个类型,就像list、tuple和str一样

    3、键类型:字典的键可以是整型、浮点型、字符串或者元组,键可以为任何不可变类型

       成员资格:表达式 k in d(d为字典)查找的是键

       自动添加:即使那个键起初在字典并不存在,可以为它分配一个值,这样字典就会建立新的项

    items = [('name','Gumby'),('age',56)]
    d = dict(items)
    print d
    # {'age': 56, 'name': 'Gumby'}
    d1 = dict(name='Gumby',age=42)
    print d1
    # {'age': 42, 'name': 'Gumby'}
    # 空字典
    d2 = dict()
    print d2
    
    #自动添加
    x = {}
    x[43] = 'foobar'
    print x
    # {43: 'foobar'}
    
    # 字典操作
    people = {
        'Alice':{
            'phone':'2341',
            'addr':'Foo drive 23'
        },
        'Beth':{
            'phone':'9102',
            'addr':'Bar street 42'
        },
        'Cecil':{
            'phone':'3158',
            'addr':'Baz avenue 90'
        }
    }
    labels = {
        'phone':'phone number',
        'addr':'address'
    }
    name = raw_input('Name: ')
    
    request = raw_input('Phone Number(p) or address(a)?')
    if request=='p' : key='phone'
    if request=='a' : key='addr'
    
    if name in people : print "%s's %s is %s." % (name,labels[key],people[name][key])
    字典示例

    4、在每个转换说明符中的%字符后面,可以加上(用圆括号括起来的)键,后面再跟上其他说明元素

    phonebook = {'Beth':'9102','Alice':'2341','Cecil':'3258'}
    print "Cecil's phone number is %(Cecil)s" % phonebook
    # Cecil's phone number is 3258
    字典特殊格式化

    5、字典方法:

      clear方法清除字典中所有的项,无返回值(或者说返回None)

      copy方法返回一个具有相同键值对的新字典(这个方法实现的是浅复制shallow copy),替换值的时候,原字典不受影响.但是如果修改了某个值(不是替换,而是修改),原字典也会改变.使用copy模块中的deepcopy可以避免这个问题

      fromkeys方法使用给定的键建立新的字典,每个键默认对应值为None

      get方法访问字典项的方法,如果试图访问字典中不存在的项时get不会出错

      items方法将所有字典键值对返回,返回时没有特殊顺序.iteritems方法的作用大致相同,但是会返回一个迭代器对象而不是列表

      keys方法将字典中的键以列表形式返回,iterkeys方法返回字典键的迭代器

      pop方法用来获得对应于给定键的值,然后将这个键值对从字典删除

      popitem方法弹出字典的随机项

      setdefault方法能够给存在的键或者不存在的键设定相应的键值

      update方法将一个字典更新到另一个字典中,如果有相同的键则会进行覆盖

      values方法以列表的形式返回字典中的值,itervalues返回值的迭代器,返回值中可以包含重复的元素

    ## clear
    d = {}
    d['name'] = 'Gumby'
    d['age'] = 42
    print d
    # {'age': 42, 'name': 'Gumby'}
    returned_value = d.clear()
    print d
    # {}
    print returned_value
    # None
    
    x = {}
    y = x
    x['key'] = 'value'
    print y
    # {'key': 'value'}
    x = {}
    print y
    # {'key': 'value'}
    
    m = {}
    n = m
    m['key'] = 'value'
    print n
    # {'key': 'value'}
    m.clear()
    print n
    # {}
    
    ## copy
    x = {'username':'admin','machines':['foo','bar','baz']}
    y = x.copy()
    y['username'] = 'chen'
    y['machines'].remove('baz')
    print x
    # {'username': 'admin', 'machines': ['foo', 'bar']}
    print y
    # {'username': 'chen', 'machines': ['foo', 'bar']}
    
    #deepcopy
    from copy import deepcopy
    d = {}
    d['names'] =  ['Alfred','Bertrand']
    c = d.copy()
    dc = deepcopy(d)
    d['names'].append('Clive')
    print c
    # {'names': ['Alfred', 'Bertrand', 'Clive']}
    print dc
    # {'names': ['Alfred', 'Bertrand']}
    
    ## fromkeys
    fd = dict.fromkeys(['name','age','sex'])
    print fd
    # {'age': None, 'name': None, 'sex': None}
    dd = dict.fromkeys(['name','age','sex'],'unknown')
    print dd
    # {'age': 'unknown', 'name': 'unknown', 'sex': 'unknown'}
    
    ## get
    gd = {}
    # print gd['name'] # 会出错
    print gd.get('name')
    # None
    
    ## items 和 iteritems
    idt = {'title':'Python Web Site', 'url':'http://www.python.org','spam':0}
    print idt.items()
    # [('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')]
    idt.iteritems()
    print idt
    # {'url': 'http://www.python.org', 'spam': 0, 'title': 'Python Web Site'}
    
    ## keys
    kid = {'name':'jon','age':'13','sex':'male'}
    print kid.keys()
    # ['age', 'name', 'sex']
    
    ## pop
    pid = {'x':1,'y':2}
    print pid.pop('x')
    # 1
    print pid
    # {'y': 2}
    
    mid = {'1':'one','2':'two','3':'three','4':'four'}
    print mid.popitem()
    
    ## setdeafult
    sid = {}
    print sid.setdefault('name','bob')
    # bob
    print sid
    # {'name': 'bob'}
    sid['name'] = 'Gumby'
    print sid.setdefault('name','bob')
    # Gumby
    print sid
    # {'name': 'Gumby'}
    
    ## update
    n1 = {'1':'one','2':'two','3':'three'}
    n2 = {'4':'four','5':'five'}
    n1.update(n2)
    print n1
    # {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
    print n2
    # {'5': 'five', '4': 'four'}
    
    n3 = {1:'A',2:'B'}
    n4 = {2:'two',3:'C'}
    n3.update(n4)
    print n3
    # {1: 'A', 2: 'two', 3: 'C'}
    
    # values
    vas = {1:'A',2:'B',3:'C',4:'D',5:'B'}
    print vas.values()
    # ['A', 'B', 'C', 'D', 'B']
    print vas
    # {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'B'}
    print list(vas.itervalues())
    # ['A', 'B', 'C', 'D', 'B']
    字典方法
  • 相关阅读:
    (1)ASCⅡ码与一般乘除与逻辑指令
    (2)串指令的传送
    【转】伟大的代码(97年的Mekka ’97 4K Intro比赛的一等奖作品)汇编机器码
    第四次游戏革命:全息游戏 from:http://www.cnblogs.com/alamiye010/archive/2012/08/15/2640881.html
    sqlce wp
    wp7 blogs
    单例的两种实现方式
    C# event from:http://www.cnblogs.com/leslies2/archive/2012/03/22/2389318.html#a4
    wp7——sqlite数据库操作 from:http://blog.csdn.net/wp_lijin/article/details/7370790
    Linq C#增删改查
  • 原文地址:https://www.cnblogs.com/chenyanliang/p/6913706.html
Copyright © 2011-2022 走看看