美文网首页
python - dict

python - dict

作者: allenhaozi | 来源:发表于2022-10-06 09:47 被阅读0次

    dict

    for k in d:       
       print(k) 
       print(k,d.get(k))
       v = d.get(k)   
       print(k,v)
    
    for k,v in d.items(): 
       print(k,v)
    
    for x in thisdict.values():
     print(x)
    
    
    

    clear

    >>> d = {}
    >>> d['name'] = 'Gumby'
    >>> d['age'] = 42
    >>> d
    {'age': 42, 'name': 'Gumby'} 
    >>> returned_value = d.clear() >>> d
    {}
    >>> print(returned_value)
    None
    

    copy

    如你所见,当替换副本中的值时,原件不受影响。然而,如果修改副本中的值(就地修改而 不是替换),原件也将发生变化,因为原件指向的也是被修改的值(如这个示例中的'machines' 列表所示)。

    >>> x = {'username': 'admin', 'machines': ['foo', 'bar', 'baz']}
     >>> y = x.copy()
    >>> y['username'] = 'mlh'
    >>> y['machines'].remove('bar')
    >>> y
    {'username': 'mlh', 'machines': ['foo', 'baz']} 
    >>> x
    {'username': 'admin', 'machines': ['foo', 'baz']}
    

    deepcopy

    >>> from copy import deepcopy
    >>> d = {}
    >>> d['names'] = ['Alfred', 'Bertrand'] 
    >>> c = d.copy()
    >>> dc = deepcopy(d)
    >>> d['names'].append('Clive')
    >>> c
    {'names': ['Alfred', 'Bertrand', 'Clive']} 
    >>> dc
    {'names': ['Alfred', 'Bertrand']}
    

    fromkeys

    方法fromkeys创建一个新字典,其中包含指定的键,且每个键对应的值都是None。

    >>> {}.fromkeys(['name', 'age']) 
    {'age': None, 'name': None}
    

    get

    >>> d = {}
    
    >>> print(d.get('name'))
    None
    
    >>> d.get('name', 'N/A') 
    'N/A'
    
    >>> d['name'] = 'Eric' 
    >>> d.get('name') 
    'Eric'
    
    

    items

    >>> d = {'title': 'Python Web Site', 'url': 'http://www.python.org', 'spam': 0} 
    >>> d.items()
    dict_items([('url', 'http://www.python.org'), ('spam', 0), ('title', 'Python Web Site')])
    
    >>> it = d.items() 
    >>> len(it)
    3
    >>> ('spam', 0) in it 
    True
    
    

    keys

    方法keys返回一个字典视图,其中包含指定字典中的键。

    pop

    >>> d = {'x': 1, 'y': 2} 
    >>> d.pop('x')
    1
    >>> d
    {'y': 2}
    

    popitem

    方法popitem类似于list.pop,但list.pop弹出列表中的最后一个元素,而popitem随机地弹

    update

    values

    >>> d = {}
    >>> d[1] = 1
    >>> d[2] = 2
    >>> d[3] = 3
    >>> d[4] = 1
    >>> d.values() 
    dict_values([1, 2, 3, 1])
    

    相关文章

      网友评论

          本文标题:python - dict

          本文链接:https://www.haomeiwen.com/subject/mrtbartx.html