Home > Mobile >  How to get the value of a random dict from a list of dict?
How to get the value of a random dict from a list of dict?

Time:11-02

I am making a noob game in which the program compares two people's followers and find which is larger. The code is like this:

import random

names = [
    {"khloekardashian": 193},
    {"kyliejenner": 279},
    {"kimkardashian": 261},
    {"kendalljenner": 197},
    {"cristiano": 361},
    {"leomessi": 278},
    {"Instagram": 478},
    {"THe Rock": 276},
    {"Ariana Grande": 273},
    {"Selena gomez": 270}]
ran=random.randrange(0,9)
rann=random.randrange(0,9)

act1 = names[ran]
act2 = names[rann]
print("which of the following has more followers or are same")
print(act1)
print("OR")
print(act2)
user=int(input("enter only 1,2,="))
score1=
if user == 1:

This is incomplete, I want to retrieve the value of dict stored in act1 and act2.

CodePudding user response:

I would suggest using random.choice() function to select the random dictionaries. Once you have those, you can extract the values within them as shown:

import random

names = [
    {"khloekardashian": 193},
    {"kyliejenner": 279},
    {"kimkardashian": 261},
    {"kendalljenner": 197},
    {"cristiano": 361},
    {"leomessi": 278},
    {"Instagram": 478},
    {"The Rock": 276},
    {"Ariana Grande": 273},
    {"Selena gomez": 270}]

act1 = random.choice(names)
act2 = random.choice(names)

name1, followers1 = tuple(act1.items())[0]
name2, followers2 = tuple(act2.items())[0]
print("Which of the following has more followers or are same?")
print(name1)
print("OR")
print(name2)

#user = int(input("enter only 1,2,="))
#score1 =
#if user == 1:

CodePudding user response:

Using a single dict is "short" and straightforward:

import random

names = {"khloekardashian": 193,
    "kyliejenner": 279,
    "kimkardashian": 261,
    "kendalljenner": 197,
    "cristiano": 361,
    "leomessi": 278,
    "Instagram": 478,
    "THe Rock": 276,
    "Ariana Grande": 273,
    "Selena gomez": 270}
act1,act2 = random.sample(names.keys(),2)

##keeping original code here
print("which of the following has more followers or are same")
print(act1)
print("OR")
print(act2)
user=int(input("enter only 1,2,="))

#answering True or False
if user == 1:
    return names[act1] > names[act2]
elif user == 2:
    return names[act2] > names[act1]
else:
    return names[act1] == names[act2]

  • Related