如何在字典中搜索键值对

时间:2016-04-25 05:14:31

标签: python

我有一个包含字典元素的列表(用户),格式如下

{'id': 1, 'username': 'abc', 'password':'xyz'}

我可以遍历列表并使用python" s"在"中为用户名应用if条件运算符使用变量值。像

这样的东西
user = abc
if user in users:
    do something here

我尝试使用if循环,但它的工作原理非常好,但我想在"中使用"或任何其他运营商。我也试过这个:

dict = "{\"username\":\"" + "myuser" + "\"}"
if dict in users:
      do something

2 个答案:

答案 0 :(得分:0)

您可以使用next运算符来获取users列表中的第一个匹配元素:

>>> users = [{'id': 1, 'username': 'abc', 'password':'xyz'}, {'id': 2, 'username': 'def', 'password':'zyx'}]

# getting the user with username 'def'
>>> next((user for user in users if user['username'] == 'def'), None)
{'id': 2, 'password': 'zyx', 'username': 'def'}

答案 1 :(得分:0)

for key, value in dict.iteritems():
    if key=='user':
        if value=='abc':
            //do something

注意:对于Python 3.x,iteritems()已被简单的items()替换。

相关问题