如何打印字典的键?
- 2025-04-15 09:20:00
- admin 原创
- 27
问题描述:
我想打印一个特定的 Python 字典键:
mydic = {
"key_name": "value"
}
现在我可以检查是否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'
指代键!:)
解决方案 1:
根据定义,字典可以包含任意数量的键。没有所谓的“键”。你有一个keys()
方法,它会返回一个list
包含所有键的 Python 文件,还有一个iteritems()
方法,它会返回键值对,所以
for key, value in mydic.iteritems() :
print key, value
Python 3 版本:
for key, value in mydic.items() :
print (key, value)
所以你掌握了键,但它们只有与值结合才真正有意义。希望我理解了你的问题。
解决方案 2:
此外,您还可以使用....
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
解决方案 3:
嗯,我认为您可能想要做的是打印字典中的所有键及其各自的值?
如果是的话,您需要以下内容:
for key in mydic:
print "the key name is" + key + "and its value is" + mydic[key]
确保使用“+”而不是“,”号。我认为逗号会将每一项放在单独的行,而“+”号会将它们放在同一行。
解决方案 4:
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()
解决方案 5:
因此,该键的名称'key_name'
是'key_name'
print('key_name')
或者任何代表它的变量。
解决方案 6:
在 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))))
解决方案 7:
既然我们都在猜测“打印键名”是什么意思,我就来试试。或许你想要一个函数,从字典中获取一个值,然后找到对应的键?反向查找?
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()}
解决方案 8:
# 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('
'.join(f'{key}: {value}' for key, value in dict.items()))
# yields:
# a: 1
# b: 2
编辑:针对 python 3 的 f 字符串进行了更新...
解决方案 9:
确保做到
dictionary.keys()
而不是
dictionary.keys
解决方案 10:
import pprint
pprint.pprint(mydic.keys())
解决方案 11:
或者你可以按照以下方式进行:
for key in my_dict:
print key, my_dict[key]
解决方案 12:
dict = {'name' : 'Fred', 'age' : 100, 'employed' : True }
# Choose key to print (could be a user input)
x = 'name'
if x in dict.keys():
print(x)
解决方案 13:
使用有什么问题'key_name'
,即使它是一个变量?
解决方案 14:
这可能是仅检索键名称的最快方法:
mydic = {}
mydic['key_name'] = 'value_name'
print mydic.items()[0][0]
结果:
key_name
将转换dictionary
为list
然后列出第一个元素,即整体,dict
然后列出该元素的第一个值,即:key_name
解决方案 15:
我查阅了这个问题,因为我想知道如果我的字典只有一个条目,如何检索“键”的名称。就我而言,键对我来说是未知的,而且可能是任意数量的值。以下是我得出的结论:
dict1 = {'random_word': [1,2,3]}
key_name = str([key for key in dict1]).strip("'[]'")
print(key_name) # equal to 'random_word', type: string.
解决方案 16:
我将这个答案添加为此处( https://stackoverflow.com/a/5905752/1904943 )的其他答案之一,该答案已过时(Python 2; iteritems
),并且所提供的代码 - 如果按照该答案评论中建议的解决方法针对 Python 3 进行更新 - 则会默默地无法返回所有相关数据。
背景
我有一些代谢数据,以图表(节点、边……)的形式表示。这些数据的字典表示形式如下:键的形式为(604, 1037, 0)
(表示源节点、目标节点以及边的类型),值的形式为5.3.1.9
(表示EC酶代码)。
查找给定值的键
以下代码正确找到了我的键和给定的值:
def k4v_edited(my_dict, value):
values_list = []
for k, v in my_dict.items():
if v == value:
values_list.append(k)
return values_list
print(k4v_edited(edge_attributes, '5.3.1.9'))
## [(604, 1037, 0), (604, 3936, 0), (1037, 3936, 0)]
而此代码仅返回第一个(可能是多个匹配的)键:
def k4v(my_dict, value):
for k, v in my_dict.items():
if v == value:
return k
print(k4v(edge_attributes, '5.3.1.9'))
## (604, 1037, 0)
后者代码,简单地iteritems
用替换 进行更新items
,无法返回(604, 3936, 0), (1037, 3936, 0
。
解决方案 17:
尝试一下:
def name_the_key(dict, key):
return key, dict[key]
mydict = {'key1':1, 'key2':2, 'key3':3}
key_name, value = name_the_key(mydict, 'key2')
print 'KEY NAME: %s' % key_name
print 'KEY VALUE: %s' % value
解决方案 18:
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
解决方案 19:
如果您想获取单个值的键,以下内容会有所帮助:
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()), \n "Enter a valid 'Value'")
print(c)
扫码咨询,免费领取项目管理大礼包!