Ben*_*min 190 python dictionary key
我想打印一个特定的Python字典键:
mydic = {}
mydic['key_name'] = 'value_name'
Run Code Online (Sandbox Code Playgroud)
现在我可以查看是否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']
Run Code Online (Sandbox Code Playgroud)
有没有name_the_key()方法可以打印密钥名称?
编辑:
好的,非常感谢你们的反应!:)我意识到我的问题没有很好的表达和琐碎.我只是感到困惑,因为我意识到key_name和mydic['key_name']两个不同的东西,我认为打印key_name出字典上下文是不正确的.但实际上我可以简单地使用'key_name'来指代密钥!:)
jua*_*nza 341
根据定义,字典具有任意数量的键.没有"钥匙".你有keys()方法,它给你一个list所有键的python ,你有iteritems()方法,它返回键值对,所以
for key, value in mydic.iteritems() :
print key, value
Run Code Online (Sandbox Code Playgroud)
Python 3版本:
for key, value in mydic.items() :
print (key, value)
Run Code Online (Sandbox Code Playgroud)
所以你有一个关键的句柄,但它们只是意味着如果耦合到一个值.我希望我理解你的问题.
小智 47
另外你可以使用....
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
Run Code Online (Sandbox Code Playgroud)
Dom*_*tos 32
嗯,我认为您可能想要做的是打印字典中的所有键及其各自的值?
如果是这样,您需要以下内容:
for key in mydic:
print "the key name is" + key + "and its value is" + mydic[key]
Run Code Online (Sandbox Code Playgroud)
确保你也使用+'而不是'.逗号会将每个项目放在一个单独的行上,我想,加号会把它们放在同一行.
ade*_*190 30
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
Run Code Online (Sandbox Code Playgroud)
注意:在Python 3中,dic.iteritems()被重命名为dic.items()
既然我们都在试图猜测"打印一个关键名称"可能意味着什么,我会捅它.也许你想要一个从字典中获取值并找到相应键的函数?反向查找?
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
Run Code Online (Sandbox Code Playgroud)
请注意,许多键可能具有相同的值,因此此函数将返回一些具有该值的键,可能不是您想要的键.
如果您需要经常这样做,那么构造反向字典是有意义的:
d_rev = dict(v,k for k,v in d.iteritems())
Run Code Online (Sandbox Code Playgroud)
# 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
Run Code Online (Sandbox Code Playgroud)
编辑:更新了 python 3 的 f 字符串...
确保做
dictionary.keys()
Run Code Online (Sandbox Code Playgroud)
而不是
dictionary.keys
Run Code Online (Sandbox Code Playgroud)
在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))))
Run Code Online (Sandbox Code Playgroud)