问题:如何打印字典的键?

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

I would like to print a specific Python dictionary key:

mydic = {}
mydic['key_name'] = 'value_name'

Now I can check if mydic.has_key('key_name'), but what I would like to do is print the name of the key 'key_name'. Of course I could use mydic.items(), but I don’t want all the keys listed, merely one specific key. For instance I’d expect something like this (in pseudo-code):

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

Is there any name_the_key() method to print a key name?


Edit: OK, thanks a lot guys for your reactions! :) I realise my question is not well formulated and trivial. I just got confused because i realised key_name and mydic['key_name'] are two different things and i thought it would incorrect to print the key_name out of the dictionary context. But indeed i can simply use the ‘key_name’ to refer to the key! :)


回答 0

根据定义,字典具有任意数量的键。没有“钥匙”。您有keys()方法,可以为您提供list所有键的python ,并且您有iteritems()方法,可以返回键-值对,因此

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

Python 3版本:

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

因此,您在键上有一个手柄,但是如果将其与值耦合,它们实际上仅意味着意义。我希望我理解你的问题。

A dictionary has, by definition, an arbitrary number of keys. There is no “the key”. You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so

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

Python 3 version:

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

So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.


回答 1

此外,您可以使用…。

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

Additionally you can use….

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

回答 2

嗯,我想您可能想做的是打印字典中的所有键及其各自的值?

如果是这样,您需要以下内容:

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

确保您也使用+而不是’。我认为逗号会将每一项放在单独的行中,加号会将它们放在同一行中。

Hmm, I think that what you might be wanting to do is print all the keys in the dictionary and their respective values?

If so you want the following:

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

Make sure you use +’s instead of ,’ as well. The comma will put each of those items on a separate line I think, where as plus will put them on the same line.


回答 3

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()

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

Note:In Python 3, dic.iteritems() was renamed as dic.items()


回答 4

因此,键“ key_name”的名称为key_name,print 'key_name'或者是您代表它的任何变量。

The name of the key ‘key_name’ is key_name, therefore print 'key_name' or whatever variable you have representing it.


回答 5

在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))))

In 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))))

回答 6

由于我们都在尝试猜测“打印键名”的含义,因此我将对其进行介绍。也许您想要一个从字典中获取一个值并找到相应键的函数?反向查询?

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())

Since we’re all trying to guess what “print a key name” might mean, I’ll take a stab at it. Perhaps you want a function that takes a value from the dictionary and finds the corresponding key? A reverse lookup?

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

Note that many keys could have the same value, so this function will return some key having the value, perhaps not the one you intended.

If you need to do this frequently, it would make sense to construct the reverse dictionary:

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

回答 7

或者,您可以按照以下方式进行操作:

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

Or you can do it that manner:

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

回答 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('\n'.join(f'{key}: {value}' for key, value in dict.items()))


# yields:
# a: 1
# b: 2

编辑:更新为python 3的f字符串…

# 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

Edit: Updated for python 3’s f-strings…


回答 9

确保做

dictionary.keys()
# rather than
dictionary.keys

Make sure to do

dictionary.keys()
# rather than
dictionary.keys

回答 10

'key_name'即使使用变量,使用它又有什么问题呢?

What’s wrong with using 'key_name' instead, even if it is a variable?


回答 11

import pprint
pprint.pprint(mydic.keys())
import pprint
pprint.pprint(mydic.keys())

回答 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)
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

可能是仅检索键名的最快方法:

mydic = {}
mydic['key_name'] = 'value_name'

print mydic.items()[0][0]

结果:

key_name

将转换dictionary为,list然后列出第一个元素是整体,dict然后列出该元素的第一个值:key_name

Probably the quickest way to retrieve only the key name:

mydic = {}
mydic['key_name'] = 'value_name'

print mydic.items()[0][0]

Result:

key_name

Converts the dictionary into a list then it lists the first element which is the whole dict then it lists the first value of that element which is: key_name


回答 14

我查询了这个问题,因为如果我的字典只有一个条目,我想知道如何检索“键”的名称。就我而言,密钥对我来说并不为人所知,可以是任何东西。这是我想出的:

dict1 = {'random_word': [1,2,3]}
key_name = str([key for key in dict1]).strip("'[]'")        
print(key_name)  # equal to 'random_word', type: string.

I looked up this question, because I wanted to know how to retrieve the name of “the key” if my dictionary only had one entry. In my case, the key was unknown to me and could be any number of things. Here is what I came up with:

dict1 = {'random_word': [1,2,3]}
key_name = str([key for key in dict1]).strip("'[]'")        
print(key_name)  # equal to 'random_word', type: string.

回答 15

试试这个:

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

Try this:

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

回答 16

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

回答 17

如果要获取单个值的键,则以下方法将有所帮助:

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方式:

c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
     "Enter a valid 'Value'")
print(c)

If you want to get the key of a single value, the following would help:

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

In pythonic way:

c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
     "Enter a valid 'Value'")
print(c)

回答 18

我将这个答案添加为此处的其他答案之一(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)

后者的代码天真地更新iteritemsitems,无法返回(604, 3936, 0), (1037, 3936, 0

I’m adding this answer as one of the other answers here (https://stackoverflow.com/a/5905752/1904943) is dated (Python 2; iteritems), and the code presented — if updated for Python 3 per the suggested workaround in a comment to that answer — silently fails to return all relevant data.


Background

I have some metabolic data, represented in a graph (nodes, edges, …). In a dictionary representation of those data, keys are of the form (604, 1037, 0) (representing source and target nodes, and the edge type), with values of the form 5.3.1.9 (representing EC enzyme codes).

Find keys for given values

The following code correctly finds my keys, given values:

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)]

whereas this code returns only the first (of possibly several matching) keys:

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)

The latter code, naively updated replacing iteritems with items, fails to return (604, 3936, 0), (1037, 3936, 0.


回答 19

要访问数据,您需要执行以下操作:

foo = {
    "foo0": "bar0",
    "foo1": "bar1",
    "foo2": "bar2",
    "foo3": "bar3"
}
for bar in foo:
  print(bar)

或者,要访问该值,只需从键中调用它即可: foo[bar]

To access the data, you’ll need to do this:

foo = {
    "foo0": "bar0",
    "foo1": "bar1",
    "foo2": "bar2",
    "foo3": "bar3"
}
for bar in foo:
  print(bar)

Or, to access the value you just call it from the key: foo[bar]


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。