faith
faith

Reputation: 89

How to exclude a specific element in a dictionary?

I want to work with a random name from my_dict , except for the name "name300000.&**" , I want to skip it and pass to another name when choice(my_dict.values()) = "name300000.&**". So I did the following, but I am looking for a better solution ?

from random import choice
my_dict = {1: "name1", 2: "name2", 3:"name300000.&**", 4:"name4"}
if "name3" in choice(my_dict.values()):
    pass
name = choice(my_dict.values())

Upvotes: 2

Views: 1642

Answers (3)

Krzysztof
Krzysztof

Reputation: 147

You can simply use set difference function to remove unwanted values:

from random import choice
my_dict = {1: "name1", 2: "name2", 3:"name300000.&**", 4:"name4"}
name = choice(list(set(my_dict.values()).difference({"name300000.&**"})))

Upvotes: 1

npk
npk

Reputation: 1810

You can simply do

name = choice(tuple(set(my_dict.values()) - {"name300000.&**"}))

Upvotes: 2

lorenzozane
lorenzozane

Reputation: 1279

This is a possible solution:

from random import choice
my_dict = {1: "name1", 2: "name2", 3:"name300000.&**", 4:"name4"}

name = choice(list(my_dict.values()))
while name == "name300000.&**":
    name = choice(my_dict.values())

print(name)

Or, another possible solution is:

from random import choice
my_dict = {1: "name1", 2: "name2", 3:"name300000.&**", 4:"name4"}


while True:
    name = choice(list(my_dict.values()))
    if name != "name300000.&**":
        break

print(name)

The point is that you have to emulate a do while loop to correctly solve this problem, and in python, since it is not natively present, you can write in these ways.

Upvotes: 1

Related Questions