python怎么打印字典_关于python:如何打印字典的密钥?

我想打印一个特定的Python字典键:

1

2mydic = {}

mydic['key_name'] = 'value_name'

现在我可以检查是否mydic.has_key('key_name'),但我想要做的是打印密钥'key_name'的名称。 当然我可以使用mydic.items(),但我不希望列出所有的键,只需要一个特定的键。 例如,我期待这样的事情(在伪代码中):

1print"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'来指代密钥!:)

如果你知道你想要的具体密钥是什么,嗯,你已经知道密钥是什么了。

根据定义,字典具有任意数量的键。没有"钥匙"。你有keys()方法,它给你一个python list的所有键,你有iteritems()方法,它返回键值对,所以

1

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

print key, value

Python 3版本:

1

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

print (key, value)

所以你有一个关键的句柄,但它们只是意味着如果耦合到一个值。我希望我理解你的问题。

虽然这在Python 2.7中对我很有效,但在Py3k中有什么替代方案?我知道.iteritems()不再受支持了......

@PolyShell是python 3中的替代方案,如果这就是Py3k的意思(我已经离开了python一段时间了)它.items()。我添加了一个例子。

.items()适用于2.7和3.x.

@Bibhas他们都工作,但语义不同。 items()返回python 2.x中的列表。

另外你可以使用....

1

2

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

print(dictionary.keys()) #prints keys

print(dictionary.values()) #prints values

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

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

1

2for key in mydic:

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

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

逗号会将它们保留在同一行,但在"is"和key之间插入空格等。如果使用+,则需要在字符串中添加额外的填充。键和值也不一定是字符串,在这种情况下逗号将使用str(键)和str(值),而+将导致错误

这是我知道不对的答案,因为OP说,"我不希望列出所有的密钥。"

出于某种原因,我想到了逗号;你是对的。我也重新阅读了这个问题,似乎我们都把'all'都用粗体 - 我的坏。

1

2

3

4

5

6

7

8

9

10

11

12

13dic = {"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,因此是print 'key_name'或您表示它的任何变量。

既然我们都在试图猜测"打印一个关键名称"可能意味着什么,我会捅它。也许你想要一个从字典中获取值并找到相应键的函数?反向查找?

1

2

3

4

5def 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

请注意,许多键可能具有相同的值,因此此函数将返回一些具有该值的键,可能不是您想要的键。

如果您需要经常这样做,那么构造反向字典是有意义的:

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

注意(如上所述)iteritems在Python 3中变成了简单的"项目"。

警告:如果将iteritems更改为items,则如最初显示的那样,此答案将仅返回第一个键 - 如果有多个匹配项。要解决此问题,请在for loop(values_list = [])之前创建一个空白列表,然后在if循环中将键附加到此列表(values_list.append(k))。最后,将return语句(return values_list)移到for循环之外。

或者你可以这样做:

1

2for 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

2import pprint

pprint.pprint(mydic.keys())

docs.python.org/2/library/pprint.html#pprint.pprint

一定要做

1

2

3dictionary.keys()

# rather than

dictionary.keys

使用'key_name'会出现什么问题,即使它是变量?

可能是仅检索密钥名称的最快方法:

1

2

3

4mydic = {}

mydic['key_name'] = 'value_name'

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

结果:

1key_name

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

为什么要检索这个值呢?

1

2

3

4

5

6

7dict = {'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; iteritems),并提供代码 - 如果已更新为Python 3根据对该答案的评论中建议的解决方法 - 无声地无法返回所有相关数据。

背景

我有一些代谢数据,用图表表示(节点,边缘......)。在这些数据的字典表示中,键的形式为(604, 1037, 0)(表示源节点和目标节点,以及边缘类型),其值为5.3.1.9(表示EC酶代码)。

查找给定值的键

以下代码正确找到我的键,给定值:

1

2

3

4

5

6

7

8

9def 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

7def 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。

如果要获取单个值的键,以下内容将有所帮助:

1

2

3

4def 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

3c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \

"Enter a valid 'Value'")

print(c)

1

2key_name = '...'

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

我查了一下这个问题,因为如果我的字典只有一个条目,我想知道如何检索"密钥"的名称。就我而言,关键是我不知道的,可能是任何数量的东西。这是我想出的:

1

2

3dict1 = {'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

8def 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值