问题:如何直接在Python中获取字典键作为变量(而不是从值中搜索)?

对不起这个基本问题,但是我的搜索没有发现什么,除了如何根据其值获取字典的键外,我不希望使用它,因为我只想要键的文本/名称,并且担心搜索如果字典中有很多条目,按值排序可能最终会返回2个或更多键…我想做的是:

mydictionary={'keyname':'somevalue'}
for current in mydictionary:

   result = mydictionary.(some_function_to_get_key_name)[current]
   print result
   "keyname"

这样做的原因是我将这些信息打印到文档中,并且在执行此操作时要使用键名和值

我看过下面的方法,但这似乎只是返回键的值

get(key[, default])

Sorry for this basic question but my searches on this are not turning up anything other than how to get a dictionary’s key based on its value which I would prefer not to use as I simply want the text/name of the key and am worried that searching by value may end up returning 2 or more keys if the dictionary has a lot of entries… what I am trying to do is this:

mydictionary={'keyname':'somevalue'}
for current in mydictionary:

   result = mydictionary.(some_function_to_get_key_name)[current]
   print result
   "keyname"

The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this

I have seen the method below but this seems to just return the key’s value

get(key[, default])

回答 0

您应该使用以下方法遍历密钥:

for key in mydictionary:
   print "key: %s , value: %s" % (key, mydictionary[key])

You should iterate over keys with:

for key in mydictionary:
   print "key: %s , value: %s" % (key, mydictionary[key])

回答 1

如果要打印键和值,请使用以下命令:

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

If you want to access both the key and value, use the following:

Python 2:

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

Python 3:

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

回答 2

这样做的原因是我将这些信息打印到文档中,并且在执行此操作时要使用键名和值

基于以上要求,这是我的建议:

keys = mydictionary.keys()
keys.sort()

for each in keys:
    print "%s: %s" % (each, mydictionary.get(each))

The reason for this is that I am printing these out to a document and I want to use the key name and the value in doing this

Based on the above requirement this is what I would suggest:

keys = mydictionary.keys()
keys.sort()

for each in keys:
    print "%s: %s" % (each, mydictionary.get(each))

回答 3

如果字典包含这样的一对:

d = {'age':24}

那么你可以得到

field, value = d.items()[0]

对于Python 3.5,请执行以下操作:

key = list(d.keys())[0]

If the dictionary contains one pair like this:

d = {'age':24}

then you can get as

field, value = d.items()[0]

For Python 3.5, do this:

key = list(d.keys())[0]

回答 4

keys=[i for i in mydictionary.keys()] 要么 keys = list(mydictionary.keys())

keys=[i for i in mydictionary.keys()] or keys = list(mydictionary.keys())


回答 5

就如此容易:

mydictionary={'keyname':'somevalue'}
result = mydictionary.popitem()[0]

您将修改字典,并应首先对其进行复制

As simple as that:

mydictionary={'keyname':'somevalue'}
result = mydictionary.popitem()[0]

You will modify your dictionary and should make a copy of it first


回答 6

您可以简单地使用*它来解开字典键。例:

d = {'x': 1, 'y': 2}
t = (*d,)
print(t) # ('x', 'y')

You could simply use * which unpacks the dictionary keys. Example:

d = {'x': 1, 'y': 2}
t = (*d,)
print(t) # ('x', 'y')

回答 7

遍历字典(i)将返回键,然后使用它(i)获取值

for i in D:
    print "key: %s, value: %s" % (i, D[i])

Iterate over dictionary (i) will return the key, then using it (i) to get the value

for i in D:
    print "key: %s, value: %s" % (i, D[i])

回答 8

对于python 3如果只想获取密钥,请使用它。如果需要这些值,请用print(values)替换print(key)。

for key,value in my_dict:
  print(key)

For python 3 If you want to get only the keys use this. Replace print(key) with print(values) if you want the values.

for key,value in my_dict:
  print(key)

回答 9

有时我要做的是创建另一个字典,以便能够以我需要的方式访问任何需要作为字符串访问的字典。然后,我遍历多个字典中的匹配键,以构建例如带有第一列作为描述的表。

dict_names = {'key1': 'Text 1', 'key2': 'Text 2'}
dict_values = {'key1': 0, 'key2': 1} 

for key, value in dict_names.items():
    print('{0} {1}'.format(dict_names[key], dict_values[key])

您可以轻松地为大量的字典匹配数据(我喜欢这样的事实,使用字典,您总是可以引用众所周知的键名)

是的,我使用字典来存储函数的结果,所以我不必每次只调用一次函数就运行这些函数,然后随时访问结果。

编辑:在我的示例中,键名并不重要(我个人喜欢使用相同的键名,因为可以更轻松地从我的任何匹配字典中选择一个值),只需确保每个词典中的键数为相同

What I sometimes do is I create another dictionary just to be able whatever I feel I need to access as string. Then I iterate over multiple dictionaries matching keys to build e.g. a table with first column as description.

dict_names = {'key1': 'Text 1', 'key2': 'Text 2'}
dict_values = {'key1': 0, 'key2': 1} 

for key, value in dict_names.items():
    print('{0} {1}'.format(dict_names[key], dict_values[key])

You can easily do for a huge amount of dictionaries to match data (I like the fact that with dictionary you can always refer to something well known as the key name)

yes I use dictionaries to store results of functions so I don’t need to run these functions everytime I call them just only once and then access the results anytime.

EDIT: in my example the key name does not really matter (I personally like using the same key names as it is easier to go pick a single value from any of my matching dictionaries), just make sure the number of keys in each dictionary is the same


回答 10

您可以通过将dict键和值强制转换为列表来执行此操作。也可以为项目完成。

例:

f = {'one': 'police', 'two': 'oranges', 'three': 'car'}
list(f.keys())[0] = 'one'
list(f.keys())[1] = 'two'

list(f.values())[0] = 'police'
list(f.values())[1] = 'oranges'

You can do this by casting the dict keys and values to list. It can also be be done for items.

Example:

f = {'one': 'police', 'two': 'oranges', 'three': 'car'}
list(f.keys())[0] = 'one'
list(f.keys())[1] = 'two'

list(f.values())[0] = 'police'
list(f.values())[1] = 'oranges'

回答 11

轻松地更改键和值的位置,然后使用值获取键,字典中的键可以具有相同的值,但它们(键)应该不同。例如,如果您有一个列表,并且列表的第一个值是问题的关键,而其他值则是第一个值的规范:

list1=["Name",'ID=13736','Phone:1313','Dep:pyhton']

您可以通过以下循环在Dictionary中轻松保存和使用数据:

data_dict={}
for i in range(1, len(list1)):
     data_dict[list1[i]]=list1[0]
print(data_dict)
{'ID=13736': 'Name', 'Phone:1313': 'Name', 'Dep:pyhton': 'Name'}

那么您可以根据任何输入值找到键(名称)。

easily change the position of your keys and values,then use values to get key, in dictionary keys can have same value but they(keys) should be different. for instance if you have a list and the first value of it is a key for your problem and other values are the specs of the first value:

list1=["Name",'ID=13736','Phone:1313','Dep:pyhton']

you can save and use the data easily in Dictionary by this loop:

data_dict={}
for i in range(1, len(list1)):
     data_dict[list1[i]]=list1[0]
print(data_dict)
{'ID=13736': 'Name', 'Phone:1313': 'Name', 'Dep:pyhton': 'Name'}

then you can find the key(name) base on any input value.


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