如何打印字典的键?

294
我想要打印出特定的Python字典键:
mydic = {}
mydic['key_name'] = 'value_name'

现在我可以检查mydic.has_key('key_name'),但我想做的是打印键'key_name'的名称。当然,我可以使用mydic.items(),但我不想要所有列出的键,只想要一个特定的键。例如,我期望像这样的结果(伪代码):

print "the key name is", mydic['key_name'].name_the_key(), "and its value is", mydic['key_name']

有没有name_the_key()方法以打印键名?


编辑: 好的,非常感谢大家的回答! :) 我意识到我的问题没有表述清楚并且很琐碎。我只是有点混淆了,因为我意识到'key_name'mydic['key_name']是两个不同的东西,我认为在字典上下文之外打印'key_name'会不正确。但实际上我可以简单地使用'key_name'来引用键! :)


24
如果你知道你想要的特定密钥是什么,那么你已经知道这个密钥是什么了。 - Wooble
是的,但能够使用代码检索密钥仍然非常有帮助,这样您就可以执行诸如确定其类型(例如 int32 vs. int64)之类的操作。 - KBurchfiel
19个回答

479

按照定义,字典中的键是任意的。没有“the key”。你可以使用keys()方法获取Python list中的所有键,也可以使用iteritems()方法返回键值对。

for key, value in mydic.iteritems() :
    print key, value

Python 3 版本:

for key, value in mydic.items() :
    print (key, value)

那么你已经掌握了这些键,但只有与一个值关联时它们才有意义。我希望我已经理解了你的问题。


1
虽然在Python 2.7中这个方法对我非常有效,但在Py3k中有什么替代方法吗?我知道.iteritems()已不再被支持... - Piper
7
如果你所说的 Py3k 是指 Python 3 的话,它的替代方案是 .items()。我加了一个例子。 - juanchopanza
1
@Bibhas 两者都可以使用,但语义不同。在Python 2.x中,items()返回一个列表。 - juanchopanza

153

另外,您可以使用...

print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values

6
.keys() 方法会打印 dict_keys([]) ,但某些人可能不需要这样。在这种情况下,您可以使用 ", ".join(dictionary)。 - thanos.a

40

嗯,我认为你想做的是打印出字典中所有的键和它们各自对应的值?

如果是这样,你需要使用以下代码:

for key in mydic:
  print "the key name is" + key + "and its value is" + mydic[key]

请确保使用加号 "+" 而不是逗号 ","。我认为逗号会将这些项放在单独的行上,而加号会将它们放在同一行上。


3
逗号会使它们在同一行,但在“is”和“key”之间插入空格等。如果使用“+”,则需要在字符串中加入额外的填充。此外,键和值不一定是字符串,在这种情况下,逗号将使用str(key)和str(value),而“+”将导致错误。 - John La Rooy
1
这是我知道不正确的一个答案,因为OP说:“我不想列出所有的键。” - Ned Batchelder
由于某些原因,我对逗号的使用有所误解;你是正确的。我也重新阅读了问题,似乎我们都将“all”加粗了 - 是我的错。 - Dominic Santos

33
dic = {"key 1":"value 1","key b":"value b"}

#print the keys:
for key in dic:
    print key

#print the values:
for value in dic.itervalues():
    print value

#print key and values
for key, value in dic.iteritems():
    print key, value

注意:在Python 3中,dic.iteritems()被重命名为dic.items()


25

键名 'key_name' 的名称是 'key_name',因此

print('key_name')

或者你所代表的任何变量。


17

在 Python 3 中:

# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}

# To print a specific key (for example key at index 1)
print([key for key in x.keys()][1])

# To print a specific value (for example value at index 1)
print([value for value in x.values()][1])

# To print a pair of a key with its value (for example pair at index 2)
print(([key for key in x.keys()][2], [value for value in x.values()][2]))

# To print a key and a different value (for example key at index 0 and value at index 1)
print(([key for key in x.keys()][0], [value for value in x.values()][1]))

# To print all keys and values concatenated together
print(''.join(str(key) + '' + str(value) for key, value in x.items()))

# To print all keys and values separated by commas
print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))

# To print all pairs of (key, value) one at a time
for e in range(len(x)):
    print(([key for key in x.keys()][e], [value for value in x.values()][e]))

# To print all pairs (key, value) in a tuple
print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))

13

由于我们都在猜测“打印键名”可能意味着什么,我来尝试一下。也许你想要一个函数,从字典中取出值并找到相应的键?一个反向查找吗?

def key_for_value(d, value):
    """Return a key in `d` having a value of `value`."""
    for k, v in d.iteritems():
        if v == value:
            return k

请注意,许多键可能具有相同的值,因此该函数将返回具有该值的某个键,可能不是您想要的那个。

如果您需要经常执行此操作,则构建反向字典将是有意义的:

d_rev = dict(v,k for k,v in d.iteritems())

Python3 更新:d.iteritems()在 Python 3+ 中已不再支持,应替换为d.items()

d_rev = {v: k for k, v in d.items()}

请注意,iteritems在Python 3中变为了简单的“items”。 - Mike
注意:如果你将 iteritems 改为 items,那么如原始显示的这个答案只会返回第一个匹配项。要解决这个问题,在 for 循环 之前创建一个空列表(values_list = []),然后在 if 循环中将键添加到该列表中(values_list.append(k))。最后,将返回语句(return values_list)移到 for 循环之外。 - Victoria Stuart

7
# highlighting how to use a named variable within a string:
mapping = {'a': 1, 'b': 2}

# simple method:
print(f'a: {mapping["a"]}')
print(f'b: {mapping["b"]}')

# programmatic method:
for key, value in mapping.items():
    print(f'{key}: {value}')

# yields:
# a 1
# b 2

# using list comprehension
print('\n'.join(f'{key}: {value}' for key, value in dict.items()))


# yields:
# a: 1
# b: 2

编辑:已更新为Python 3的f-string...


6

请务必执行

dictionary.keys()

不是...而是...
dictionary.keys

5

您还可以这样做:

for key in my_dict:
     print key, my_dict[key]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接