Programming

파이썬 사전에서 임의의 값을 얻는 방법

procodes 2020. 6. 28. 20:04
반응형

파이썬 사전에서 임의의 값을 얻는 방법


에서 무작위 쌍을 얻으려면 어떻게해야 dict합니까? 나는 당신이 나라의 수도를 추측 해야하는 게임을 만들고 있으며 무작위로 나타나기 위해 질문이 필요합니다.

dict모습처럼{'VENEZUELA':'CARACAS'}

어떻게해야합니까?


한 가지 방법 (Python 2. *)은 다음과 같습니다.

import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'OTTAWA'}
random.choice(list(d.keys()))

편집 : 원래 게시물 이후 몇 년 동안 질문이 변경되어 이제 단일 항목이 아니라 쌍을 요청합니다. 마지막 줄은 이제 다음과 같아야합니다.

country, capital = random.choice(list(d.items()))

나는 같은 문제를 해결하기 위해 이것을 썼다.

https://github.com/robtandy/randomdict

키, 값 및 항목에 O (1) 임의 액세스 할 수 있습니다.


random모듈 을 사용하지 않으려면 popitem ()을 시도해도됩니다 .

>> d = {'a': 1, 'b': 5, 'c': 7}
>>> d.popitem()
('a', 1)
>>> d
{'c': 7, 'b': 5}
>>> d.popitem()
('c', 7)

dict 는 order을 유지하지 않기 때문에 를 사용 popitem하면 임의의 순서로 항목을 얻을 수 있습니다.

또한 docs에popitem 명시된대로 사전에서 키-값 쌍 제거합니다 .

popitem ()은 사전을 파괴적으로 반복하는 데 유용합니다


>>> import random
>>> d = dict(Venezuela = 1, Spain = 2, USA = 3, Italy = 4)
>>> random.choice(d.keys())
'Venezuela'
>>> random.choice(d.keys())
'USA'

호출하여 random.choice을keys사전 (국가)의.


이 시도:

import random
a = dict(....) # a is some dictionary
random_key = random.sample(a, 1)[0]

이것은 확실히 작동합니다.


random.choice ()를 사용하지 않으려면 다음과 같이 시도하십시오.

>>> list(myDictionary)[i]
'VENEZUELA'
>>> myDictionary = {'VENEZUELA':'CARACAS', 'IRAN' : 'TEHRAN'}
>>> import random
>>> i = random.randint(0, len(myDictionary) - 1)
>>> myDictionary[list(myDictionary)[i]]
'TEHRAN'
>>> list(myDictionary)[i]
'IRAN'

원래 게시물이 쌍을 원했기 때문에 :

import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}
country, capital = random.choice(list(d.items()))

(파이썬 3 스타일)


이것은 숙제이기 때문에 :

Check out random.sample() which will select and return a random element from an list. You can get a list of dictionary keys with dict.keys() and a list of dictionary values with dict.values().


This works in Python 2 and Python 3:

A random key:

random.choice(list(d.keys()))

A random value

random.choice(list(d.values()))

A random key and value

random.choice(list(d.items()))

I am assuming that you are making a quiz kind of application. For this kind of application I have written a function which is as follows:

def shuffle(q):
"""
The input of the function will 
be the dictionary of the question
and answers. The output will
be a random question with answer
"""
selected_keys = []
i = 0
while i < len(q):
    current_selection = random.choice(q.keys())
    if current_selection not in selected_keys:
        selected_keys.append(current_selection)
        i = i+1
        print(current_selection+'? '+str(q[current_selection]))

If I will give the input of questions = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'} and call the function shuffle(questions) Then the output will be as follows:

VENEZUELA? CARACAS
CANADA? TORONTO

You can extend this further more by shuffling the options also


Try this (using random.choice from items)

import random

a={ "str" : "sda" , "number" : 123, 55 : "num"}
random.choice(list(a.items()))
#  ('str', 'sda')
random.choice(list(a.items()))[1] # getting a value
#  'num'

b = { 'video':0, 'music':23,"picture":12 } 
random.choice(tuple(b.items())) ('music', 23) 
random.choice(tuple(b.items())) ('music', 23) 
random.choice(tuple(b.items())) ('picture', 12) 
random.choice(tuple(b.items())) ('video', 0) 

참고URL : https://stackoverflow.com/questions/4859292/how-to-get-a-random-value-in-python-dictionary

반응형