How to print a dictionary's key?

2019-01-16 00:14发布

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! :)

18条回答
一夜七次
2楼-- · 2019-01-16 01:02

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)
查看更多
祖国的老花朵
3楼-- · 2019-01-16 01:06

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())
查看更多
你好瞎i
4楼-- · 2019-01-16 01:08

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.

查看更多
爷的心禁止访问
5楼-- · 2019-01-16 01:08

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

查看更多
手持菜刀,她持情操
6楼-- · 2019-01-16 01:09
# highlighting how to use a named variable within a string:
dict = {'a': 1, 'b': 2}

# simple method:
print "a %(a)s" % dict
print "b %(b)s" % dict

# programmatic method:
for key in dict:
    val = '%('+key+')s'
    print key, val % dict

# yields:
# a 1
# b 2

# using list comprehension
print "\n".join(["%s: %s" % (key, ('%('+key+')s') % dict) for key in dict])

# yields:
# a: 1
# b: 2
查看更多
唯我独甜
7楼-- · 2019-01-16 01:15
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()

查看更多
登录 后发表回答