我想打印一个特定的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”来引用键!:)


当前回答

或者你可以这样做:

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

其他回答

根据定义,字典有任意数量的键。没有“钥匙”。你有keys()方法,它给你一个包含所有键的python列表,还有iteritems()方法,它返回键值对,所以

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

Python 3版本:

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

所以你可以处理键,但它们只有在与值耦合时才有意义。我希望我已经理解了你的问题。

如果你想获取单个值的键,下面的方法会有帮助:

def get_key(b): # the value is passed to the function
    for k, v in mydic.items():
        if v.lower() == b.lower():
            return k

以python的方式:

c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
     "Enter a valid 'Value'")
print(c)
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()

在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))))
# 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-strings更新…