Python 迭代字典值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27733685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 02:11:45  来源:igfitidea点击:

Iterating over dict values

pythonpython-3.xdictionary

提问by Mike.G

If i would like to iterate over dictionary values that are stored in a tuple.

如果我想遍历存储在元组中的字典值。

i need to return the object that hold the "CI" value, i assume that i will need some kind of a for loop :

我需要返回保存“CI”值的对象,我假设我需要某种 for 循环:

z = {'x':(123,SE,2,1),'z':(124,CI,1,1)}
for i, k in db.z:
    for k in db.z[i]:
        if k == 'CI':
            return db.z[k]

i am probably missing something here, a point of reference would be good.

我可能在这里遗漏了一些东西,一个参考点会很好。

if there is a faster way doing so it would all so help greatly

如果有更快的方法这样做,这一切都会有很大帮助

采纳答案by GLHF

z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for i in z.keys(): #reaching the keys of dict
    for x in z[i]: #reaching every element in tuples
        if x=="CI": #if match found..
            print ("{} holding {}.".format(i,x)) #printing it..

This might solve your problem.

这可能会解决您的问题。

Output:

输出:

>>> 
q holding CI.
>>> 

Edit for your comment:

编辑您的评论:

def func(*args):
    mylist=[]
    z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
    for x,y in z.items():
        for t in args:
            if t in y:
                mylist.append(x)
    return mylist
print (func(1,"CI"))

Output:

输出:

>>> 
['q', 'q', 'x']
>>>  

Hope this is what you want, otherwise first method is already printing all keys, example output:

希望这是您想要的,否则第一种方法已经打印所有键,示例输出:

if x==1 or x=="CI":

>>> 
x holding 1.
q holding CI.
q holding 1.
q holding 1.
>>> 

回答by Urban48

z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for key, val in z.items():
    if 'CI' in val:
        return z[key]

回答by Hackaholic

try this:

尝试这个:

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> list(filter(lambda x:'CI' in z.get(x),z))
['z']

回答by zehnpaard

Ways to iterate over a dictionary

迭代字典的方法

First things first, there are a few ways you can loop over a dictionary.

首先,有几种方法可以遍历字典。

Looping directly over the dictionary:

直接在字典上循环:

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> for key in z:
...     print key,
...
'x' 'z'

Notice that the loop variables that get returned when you just loop over a dictionary are the keys, not the values associated with those keys.

请注意,当您遍历字典时返回的循环变量是键,而不是与这些键关联的值。

Looping over the values of a dictionary:

循环字典的值:

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> for value in z.values(): # Alternatively itervalues() for memory-efficiency (but ugly)
...     print value,
...
(123,'SE',2,1) (124,'CI',1,1)

Looping over both the keys and the values:

遍历键和值:

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> for key, value in z.items(): # Again, iteritems() for memory-efficiency
...     print key, value,
...
'x' (123,'SE',2,1) 'z' (124,'CI',1,1)

The latter two are somewhat more efficient than looping over keys and running z[key] to obtain the value. It's also arguably more readable.

后两者比循环键并运行 z[key] 来获取值更有效。它也可以说更具可读性。

Building on these...

建立在这些...

List Comprehensions

列表推导式

List comprehensionsare great. For the simple case of searching for just 'CI':

列表理解很棒。对于仅搜索“CI”的简单情况:

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> [key for key, value in z.items() if 'CI' in value]
['z']

For finding dict keys that hold several search items:

查找包含多个搜索项的字典键:

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> search_items = ('CI', 1) # Only keys that hold both CI and 1 will match
>>> [key for key, value in z.items() if all(item in value for item in search_items)]
['z']

For finding dict keys that hold any of multiple search items:

要查找包含多个搜索项中的任何一个的 dict 键:

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> search_items = ('CI', 'SE', 'JP') # Keys that hold any of the three items will match
>>> [key for key, value in z.items() if any(item in value for item in search_items)]
['x', 'z']

If the latter two look a bit too complex as one-liners, you can re-write the last bit as a separate function.

如果后两者看起来有点过于复杂,那么您可以将最后一位重写为单独的函数。

>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)}
>>> search_items = ('CI', 'SE', 'JP') # Keys that hold any of the three items will match
>>> def match_any(dict_value, search_items):
...     return any(item in dict_value for item in search_items)
...
>>> [key for key, value in z.items() if match_any(value, search_items)]
['x', 'z']

Once you get used to the [x for x in iterable if condition(x)] syntax, the format should be very easy to read and follow.

一旦你习惯了 [x for x in iterable if condition(x)] 语法,格式应该很容易阅读和遵循。

回答by franksands

There's no need to retrieve the key if you're only interested in the values:

如果您只对值感兴趣,则无需检索密钥:

In Python 2.x:

在 Python 2.x 中:

z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for value in z.itervalues():
    if 'CI' in value:
        return value

In Python 3.x:

在 Python 3.x 中:

z = {'x':(123,"SE",2,1),'q':(124,"CI",1,1)}
for value in z.values():
    if 'CI' in value:
        return value