본문 바로가기
개발/Python

파이썬의 dict에서 랜덤 값을 얻는 방법

by MinorMan 2021. 1. 14.
반응형

<질문>

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

그만큼dict처럼 보인다{'VENEZUELA':'CARACAS'}

어떻게 할 수 있습니까?


<답변1>

한 가지 방법은 다음과 같습니다.

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

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

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

<답변2>

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

https://github.com/robtandy/randomdict

키, 값 및 항목에 대한 O (1) 임의 액세스 권한이 있습니다.


<답변3>

이 시도:

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

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


<답변4>

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

전화로random.choicekeys사전 (국가)의.


<답변5>

사용하지 않으려면random모듈, 당신은 또한 시도 할 수 있습니다popitem():

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

이후dictdoesn't preserve order, 사용하여popitem당신은 그것으로부터 임의의 (엄격하게 무작위가 아닌) 순서로 아이템을 얻는다.

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

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


<답변6>

이것은 Python 2 및 Python 3에서 작동합니다.

임의의 키 :

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

임의의 값

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

임의의 키 및 값

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

<답변7>

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

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

(파이썬 3 스타일)


<답변8>

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'

<답변9>

이것이 숙제이기 때문에 :

체크 아웃random.sample()목록에서 임의의 요소를 선택하고 반환합니다. 다음을 사용하여 사전 키 목록을 가져올 수 있습니다.dict.keys()및 사전 값 목록dict.values().


<답변10>

나는 당신이 퀴즈 종류의 응용 프로그램을 만들고 있다고 가정합니다. 이러한 종류의 응용 프로그램을 위해 다음과 같은 함수를 작성했습니다.

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]))

내가 입력을 줄 경우questions = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}함수를 호출shuffle(questions)그러면 출력은 다음과 같습니다.


VENEZUELA? CARACAS
CANADA? TORONTO

옵션을 섞어서 더 확장 할 수 있습니다.


<답변11>

최신 버전의 Python (3 이후)에서는 메서드가 반환하는 객체dict.keys(),dict.values()dict.items()보기 개체입니다 *. 반복 할 수 있으므로 직접 사용random.choice지금은 목록이나 세트가 아니기 때문에 불가능합니다.

한 가지 옵션은 목록 이해력을 사용하여 작업을 수행하는 것입니다.random.choice:

import random

colors = {
    'purple': '#7A4198',
    'turquoise':'#9ACBC9',
    'orange': '#EF5C35',
    'blue': '#19457D',
    'green': '#5AF9B5',
    'red': ' #E04160',
    'yellow': '#F9F985'
}

color=random.choice([hex_color for color_value in colors.values()]

print(f'The new color is: {color}')

참조 :


<답변12>

이것을 시도하십시오 (항목에서 random.choice 사용)

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'

<답변13>

다음은 O (1) 시간에 임의의 키를 반환 할 수있는 사전 클래스 용 Python 코드입니다. (가독성을 위해이 코드에 MyPy 유형을 포함했습니다) :

from typing import TypeVar, Generic, Dict, List
import random

K = TypeVar('K')
V = TypeVar('V')
class IndexableDict(Generic[K, V]):
    def __init__(self) -> None:
        self.keys: List[K] = []
        self.vals: List[V] = []
        self.dict: Dict[K, int] = {}

    def __getitem__(self, key: K) -> V:
        return self.vals[self.dict[key]]

    def __setitem__(self, key: K, val: V) -> None:
        if key in self.dict:
            index = self.dict[key]
            self.vals[index] = val
        else:
            self.dict[key] = len(self.keys)
            self.keys.append(key)
            self.vals.append(val)

    def __contains__(self, key: K) -> bool:
        return key in self.dict

    def __len__(self) -> int:
        return len(self.keys)

    def random_key(self) -> K:
        return self.keys[random.randrange(len(self.keys))]

<답변14>

나는 다소 비슷한 솔루션을 찾아이 게시물을 찾았습니다. dict에서 여러 요소를 선택하려면 다음을 사용할 수 있습니다.

idx_picks = np.random.choice(len(d), num_of_picks, replace=False) #(Don't pick the same element twice)
result = dict ()
c_keys = [d.keys()] #not so efficient - unfortunately .keys() returns a non-indexable object because dicts are unordered
for i in idx_picks:
    result[c_keys[i]] = d[i]

<답변15>

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) 
728x90

댓글