当前位置:主页 > 资料 >

Idiomatic Python: Dictionaries
栏目分类:资料   发布日期:2017-05-28   浏览次数:

导读:本文为去找网小编(www.7zhao.net)为您推荐的Idiomatic Python: Dictionaries,希望对您有所帮助,谢谢! ##Dict comprehension Dict comprehensions can be used to create dictionaries from arbitrary key and value expressions

本文为去找网小编(www.7zhao.net)为您推荐的Idiomatic Python: Dictionaries,希望对您有所帮助,谢谢!

本文来自去找www.7zhao.net



##Dict comprehension copyright www.7zhao.net

Dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

本文来自去找www.7zhao.net

>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
 

www.7zhao.net

##Loop over dictionary keys www.7zhao.net

d = {'matthew': 'blue', 'rachel': 'green', 'raymond':'red'}

for k in d:
    print k

for k in d.keys():
    if k.startswith('r'):
        del d[k]
        
d = {k: d[k] for k in d if not k.startswith('r')}
 
copyright www.7zhao.net

##Loop over a dictionary keys and values copyright www.7zhao.net

#NOT SO GOOD
for k in d:
    print k, ' -> ', d[k]

#BETTER
for k, v in d.items():
    print k, ' -> ', v

#BEST
for k, v in d.iteritems():
    print k, ' -> ', v
 本文来自去找www.7zhao.net 

##Construct a dictionary from pairs

去找(www.7zhao.net欢迎您

from itertools import izip

names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue']

d = dict(izip(names, colors))
{'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}

d = dict(enumerate(names))
{0: 'raymond', 1: 'rachel', 2: 'matthew'}
 www.7zhao.net 

##Counting with dict 内容来自www.7zhao.net

colors = ['red', 'green', 'red', 'blue', 'green', 'red']

#NOT SO GOOD
d = {}
for color in colors:
    if color not in d:
        d[color] = 0
    d[color] += 1
{'blue': 1, 'green': 2, 'red': 3}

#BETTER
d = {}
for color in colors:
    d[color] = d.get(color, 0) + 1

#BEST
from collections import defaultdict
d = defaultdict(int)
for color in colors:
    d[color] += 1
 去找(www.7zhao.net欢迎您 

##Grouping with dict

本文来自去找www.7zhao.net

#NOT SO GOOD
d = {}
for name in names:
    key = len(name)
    if key not in d:
        d[key] = []
    d[key].append(name)
{5: ['roger', 'betty'], 6: ['rachel', 'judith'],
 7: ['raymond', 'matthew', 'melissa', 'charlie']}

#BETTER
d = {}
for name in names:
    key = len(name)
    d.setdefault(key, []).append(name)

#BEST
from collections import defaultdict
d = defaultdict(list)
for name in names:
    key = len(name)
    d[key].append(name)
 
欢迎访问www.7zhao.net

##Use popitem

www.7zhao.net

d = {'matthew': 'blue', 'rachel': 'green', 'raymond':'red'}

while d:
    key, value = d.popitem()
    print key, '-->', value
 

欢迎访问www.7zhao.net

##Linking dictionaries

本文来自去找www.7zhao.net

defaults = {'color': 'red', 'user': 'guest'}

parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args([])
command_line_args = {k: v for k, v in vars(namespace).items() if v}

#NOT SO GOOD
d = defaults.copy()
d.update(os.environ)
d.update(command_line_args)

#GOOD(ONLY FOR PYTHON 3)
d = ChainMap(command_line_args, os.environ, defaults)
 

欢迎访问www.7zhao.net

欢迎访问www.7zhao.net


本文原文地址:http://codethink.me/2014/08/09/idiomatic-python-dictionaries/

以上为Idiomatic Python: Dictionaries文章的全部内容,若您也有好的文章,欢迎与我们分享!

去找(www.7zhao.net欢迎您

下一篇:没有了
Copyright ©2008-2017去找网版权所有   皖ICP备12002049号-2 皖公网安备 34088102000435号   关于我们|联系我们| 免责声明|友情链接|网站地图|手机版