사전의 키를 인쇄하는 방법
특정 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'
:) 라고 하다. : )
사전에는 정의상 임의의 수의 키가 있습니다."열쇠"는 없습니다.이 경우,keys()
python method: python method: python method: python method.list
키 에서 'Keys'가 있습니다.iteritems()
쌍을 한다.
for key, value in mydic.iteritems() :
print key, value
Python 3 버전:
for key, value in mydic.items() :
print (key, value)
키에 대한 핸들이 있지만, 그것들은 값과 결합되어야만 의미가 있습니다.제가 당신의 질문을 이해했기를 바랍니다.
또, 다음과 같은 것도 사용할 수 있습니다.
print(dictionary.items()) #prints keys and values
print(dictionary.keys()) #prints keys
print(dictionary.values()) #prints values
음, 제 생각엔 당신이 하고 싶은 일은 사전에 있는 모든 키와 각각의 값을 인쇄하는 것 같아요.
이 경우 다음을 수행합니다.
for key in mydic:
print "the key name is" + key + "and its value is" + mydic[key]
'' 대신에 '+'를 꼭 사용하세요.쉼표는 각 항목을 별도의 행에 표시하며, 여기서 as+는 같은 행에 표시합니다.
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'
print('key_name')
어떤 변수를 가지고 있든 상관없습니다.
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))))
'키네임 인쇄'가 무슨 뜻인지 우리 모두 추측하고 있으니, 한번 시도해 보겠습니다.사전에서 값을 가져와 해당 키를 찾는 기능을 원하십니까?역방향 조회?
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())
Python3 업데이트:d.iteritems()
3 Python 3+로 .d.items()
d_rev = {v: k for k, v in d.items()}
# 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-string에 대해 업데이트됨...
꼭 해 주세요
dictionary.keys()
보다는
dictionary.keys
import pprint
pprint.pprint(mydic.keys())
또는 다음과 같은 방법으로 수행할 수 있습니다.
for key in my_dict:
print key, my_dict[key]
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)
를 사용하는 데 문제가 있는 것은 무엇입니까?'key_name'
그게 변수라도?
아마도 키 이름만 검색하는 가장 빠른 방법일 것입니다.
mydic = {}
mydic['key_name'] = 'value_name'
print mydic.items()[0][0]
결과:
key_name
를 변환합니다.dictionary
에list
그런 다음 전체인 첫 번째 요소를 나열합니다.dict
그런 다음 해당 요소의 첫 번째 값을 나열합니다.key_name
다른 답변 중 하나로 이 답변을 추가합니다(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)
후자의 코드, 순진하게 갱신된 대체iteritems
와 함께items
, 를 반환할 수 없습니다.(604, 3936, 0), (1037, 3936, 0
.
이 질문을 찾은 이유는 사전에 항목이 하나밖에 없을 때 "열쇠"의 이름을 검색하는 방법을 알고 싶었기 때문입니다.저 같은 경우에는 키를 알 수 없고 여러 가지가 있을 수 있습니다.제가 생각해낸 것은 다음과 같습니다.
dict1 = {'random_word': [1,2,3]}
key_name = str([key for key in dict1]).strip("'[]'")
print(key_name) # equal to 'random_word', type: string.
이것을 시험해 보세요.
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
key_name = '...'
print "the key name is %s and its value is %s"%(key_name, mydic[key_name])
단일 값의 키를 가져오려면 다음을 참조하십시오.
def get_key(b): # the value is passed to the function
for k, v in mydic.items():
if v.lower() == b.lower():
return k
피조니컬한 방법:
c = next((x for x, y in mydic.items() if y.lower() == b.lower()), \
"Enter a valid 'Value'")
print(c)
데이터에 액세스 하려면 , 다음의 조작을 실시할 필요가 있습니다.
foo = {
"foo0": "bar0",
"foo1": "bar1",
"foo2": "bar2",
"foo3": "bar3"
}
for bar in foo:
print(bar)
또는 키에서 호출한 값에 액세스하려면 다음 절차를 따릅니다.foo[bar]
언급URL : https://stackoverflow.com/questions/5904969/how-to-print-a-dictionarys-key
'it-source' 카테고리의 다른 글
Python Request Post(파라미터 데이터 포함) (0) | 2022.10.31 |
---|---|
Java 로깅 vs Log4J (0) | 2022.10.31 |
MySQL 데이터베이스가 XAMPP Manager-osx에서 시작되지 않음 (0) | 2022.10.30 |
테이블 'db_session'은 'DELETE'의 대상과 별도의 데이터 소스로 두 번 지정됩니다. (0) | 2022.10.30 |
vue.js 2에서 Larabel의 baseurl을 사용하려면 어떻게 해야 하나요? (0) | 2022.10.30 |