파이썬 사전에서 임의의 값을 얻는 방법
에서 무작위 쌍을 얻으려면 어떻게해야 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
'Programming' 카테고리의 다른 글
동일한 프로젝트 또는 다른 프로젝트에 단위 테스트를합니까? (0) | 2020.06.28 |
---|---|
CSS“컬러”와“글꼴 컬러” (0) | 2020.06.28 |
Linux에서 변수를 영구적으로 내보내는 방법? (0) | 2020.06.28 |
매핑 할 객체 배열없이 React.js에서 요소를 반복하고 렌더링하는 방법은 무엇입니까? (0) | 2020.06.28 |
이미지 이름을 알고있는 경우 이미지의 리소스 ID를 어떻게 얻습니까? (0) | 2020.06.28 |