How to print a dictionary's key?
我想打印一个特定的Python字典键:
1 2 | mydic = {} mydic['key_name'] = 'value_name' |
现在我可以检查是否
1 | print"the key name is", mydic['key_name'].name_the_key(),"and its value is", mydic['key_name'] |
是否有任何
编辑:
好的,非常感谢你们的反应! :)我意识到我的问题没有很好的表达和琐碎。 我只是感到困惑,因为我意识到key_name和
根据定义,字典具有任意数量的键。没有"钥匙"。你有
1 2 | for key, value in mydic.iteritems() : print key, value |
Python 3版本:
1 2 | for key, value in mydic.items() : print (key, value) |
所以你有一个关键的句柄,但它们只是意味着如果耦合到一个值。我希望我理解你的问题。
另外你可以使用....
1 2 3 | print(dictionary.items()) #prints keys and values print(dictionary.keys()) #prints keys print(dictionary.values()) #prints values |
嗯,我认为您可能想要做的是打印字典中的所有键及其各自的值?
如果是这样,您需要以下内容:
1 2 | for key in mydic: print"the key name is" + key +"and its value is" + mydic[key] |
确保你也使用+'而不是'。逗号会将每个项目放在一个单独的行中,我认为,加号会将它们放在同一行。
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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()
键'key_name'的名称是key_name,因此是
既然我们都在试图猜测"打印一个关键名称"可能意味着什么,我会捅它。也许你想要一个从字典中获取值并找到相应键的函数?反向查找?
1 2 3 4 5 | 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 |
请注意,许多键可能具有相同的值,因此此函数将返回一些具有该值的键,可能不是您想要的键。
如果您需要经常这样做,那么构造反向字典是有意义的:
1 | d_rev = dict(v,k for k,v in d.iteritems()) |
或者你可以这样做:
1 2 | for key in my_dict: print key, my_dict[key] |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # 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-strings ...
在Python 3中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # 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)))) |
1 2 | import pprint pprint.pprint(mydic.keys()) |
一定要做
1 2 3 | dictionary.keys() # rather than dictionary.keys |
使用
可能是仅检索密钥名称的最快方法:
1 2 3 4 | mydic = {} mydic['key_name'] = 'value_name' print mydic.items()[0][0] |
结果:
1 | key_name |
将
1 2 3 4 5 6 7 | 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) |
我正在添加此答案作为其中一个答案(https://stackoverflow.com/a/5905752/1904943)已过时(Python 2;
背景
我有一些代谢数据,用图表表示(节点,边缘......)。在这些数据的字典表示中,键的形式为
查找给定值的键
以下代码正确找到我的键,给定值:
1 2 3 4 5 6 7 8 9 | 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)] |
而此代码仅返回第一个(可能是几个匹配的)键:
1 2 3 4 5 6 7 | 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) |
后一个代码,天真地更新
如果要获取单个值的键,以下内容将有所帮助:
1 2 3 4 | def get_key(b): # the value is passed to the function for k, v in mydic.items(): if v.lower() == b.lower(): return k |
以pythonic方式:
1 2 3 | c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \ "Enter a valid 'Value'") print(c) |
1 2 | key_name = '...' print"the key name is %s and its value is %s"%(key_name, mydic[key_name]) |
我查了一下这个问题,因为如果我的字典只有一个条目,我想知道如何检索"密钥"的名称。就我而言,关键是我不知道的,可能是任何数量的东西。这是我想出的:
1 2 3 | dict1 = {'random_word': [1,2,3]} key_name = str([key for key in dict1]).strip("'[]'") print(key_name) # equal to 'random_word', type: string. |
试试这个:
1 2 3 4 5 6 7 8 | 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 |