如何在Python中以具体方式从键列表中获取第一个值?

时间:2016-05-20 20:31:29

标签: python dictionary

有一个词典(比如d)。如果dict.get(key, None)中不存在Nonekey会返回d

如何从密钥列表中获取第一个值(即d[key]不是None)(其中一些可能不存在于d中)?< /强>

这篇文章Pythonic way to avoid “if x: return x” statements提供了一个具体的方法。

for d in list_dicts:
    for key in keys:
        if key in d:
            print(d[key])
            break

我使用 xor operator 在一行中创建它,如

中所示
# a list of dicts
list_dicts = [  {'level0' : (1, 2), 'col': '#ff310021'},
                {'level1' : (3, 4), 'col': '#ff310011'},
                {'level2' : (5, 6), 'col': '#ff312221'}]

# loop over the list of dicts dicts, extract the tuple value whose key is like level*
for d in list_dicts:
    t = d.get('level0', None) or d.get('level1', None) or d.get('level2', None)
    col = d['col']

    do_something(t, col)

有效。这样,我只需列出所有选项(level0level3)。对于很多键(例如,从level0level100)是否有更好的方法,例如列表推导?

5 个答案:

答案 0 :(得分:4)

这一行:

x, y = d.get('level0', None) or d.get('level1', None) or d.get('level2', None)

基本上将list ['level0', 'level1', 'level2']映射到d.getNone已经是默认值;在这种情况下,无需明确说明它)。接下来,您要选择不映射到None的那个,它基本上是一个过滤器。您可以使用map()filter()内置函数(Python 3中类似延迟生成器的对象)并调用next()来获得第一个匹配项:

list_dicts = [  {'level0' : (1, 2), 'col': '#ff310021'},
                {'level1' : (3, 4), 'col': '#ff310011'},
                {'level2' : (5, 6), 'col': '#ff312221'}]
>>> l = 'level0', 'level1', 'level2'
>>> for d in list_dicts:
...     print(next(filter(None, map(d.get, l))))
...
(1, 2)
(3, 4)
(5, 6) 

答案 1 :(得分:3)

没有方便的内置功能,但您可以轻松实现它:

def getfirst(d, keys):
    for key in keys:
        if key in d:
            return d[key]
    return None

答案 2 :(得分:1)

我会使用next进行理解:

# build list of keys
levels = [ 'level' + str(i) for i in range(3) ]

for d in list_dicts:
  level_key = next(k for k in levels if d.get(k))
  level = d[level_key]

答案 3 :(得分:1)

应该适用于所有蟒蛇:

# a list of dicts
list_dicts = [{'level0': (1, 2), 'col': '#ff310021'},
              {'level1': (3, 4), 'col': '#ff310011'},
              {'level2': (5, 6), 'col': '#ff312221'}]

# Prioritized (ordered) list of keys [level0, level99]
KEYS = ['level{}'.format(i) for i in range(100)]


# loop over the list of dicts dicts, extract the tuple value whose key is
# like level*
for d in list_dicts:
    try:
        k = next(k for k in KEYS if k in d)
        t = d[k]
        col = d['col']

        do_something(t, col)
    except StopIteration:
        pass

答案 4 :(得分:1)

就像一个新奇的项目,这是一个首先使用功能组合来计算吸气剂的版本。

if 'reduce' not in globals():
    from functools import reduce

list_dicts = [  {'level0' : (1, 2), 'col': '#ff310021'},
                {'level1' : (3, 4), 'col': '#ff310011'},
                {'level2' : (5, 6), 'col': '#ff312221'}]


levels = list(map('level{}'.format, range(3)))
getter = reduce(lambda f, key: lambda dct: dct.get(key, f(dct)), reversed(levels), lambda _: None)

print(list(map(getter, list_dicts)))

# [(1, 2), (3, 4), (5, 6)]