python字典值和键

时间:2018-08-30 22:41:56

标签: python python-3.x dictionary

我有一个叫做人类的字典。我想遍历该字典,如果值小于20,则打印字典键。

humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}

4 个答案:

答案 0 :(得分:5)

John,您好,欢迎来到Stack Overflow。您对问题的描述几乎是实现该问题的完美伪代码:

# I've got dictionary called humans. 
humans = {"Danny": 33, "Jenny": 22, "Jackie": 12, "Ashley": 33}

for key, value in humans.items():  # I want to loop through that dictionary 
    if value < 20:                 # and if value is less than 20
        print(key)                 # print dictionary key.

答案 1 :(得分:3)

尝试一下:

for k, v in humans.items():
   if v > 20:
      print(k)

或者,更Python化的方式:

print([k for k, v in humans.items() if v > 20])

答案 2 :(得分:3)

使用生成器表达式尝试一下:

StringBuilder sql = new StringBuilder("UPDATE league SET season=?");
List<Integer> numValues = new ArrayList<>();
if (l.getPlayedMatches() != -1) {
    sql.append(", playedMatches=?");
    numValues.add(l.getPlayedMatches());
}
if (l.getPercentHomeWins() != -1) {
    sql.append(", percentHomeWins=?");
    numValues.add(l.getPercentHomeWins());
}
// ... more code ...
sql.append(whereClause)
   .append(" and country=?");
try (PreparedStatement stmt = conn.prepareStatement(sql.toString())) {
    int paramIdx = 0;
    stmt.setInt(++paramIdx, l.getSeason());
    for (Integer numValue : numValues)
        stmt.setInt(++paramIdx, numValue);
    stmt.setString(++paramIdx, l.getCountry());
    stmt.executeUpdate();
}

我使用逗号作为分隔符,如果需要在不同行中的每个项目,只需将result = (k for k, v in humans.items() if v > 20) print(', '.join(result)) 替换为', '

答案 3 :(得分:3)

环绕items()

您可以使用理解(不需要使用[ ],因为它已经在括号中了):

print(k for k,v in humans.items() if v > 20)

或真正循环:

for k,v in humans.items():
    if v > 20:
       print(k)