Reputation: 173
This is my code:
I create some random letters and I store them in variables, then I use this variables as keys in the dictionary. The problem is that the keys are duplicates because of the random letters. How can I fix that?
a = random.choice(string.ascii_letters).lower()
b = random.choice(string.ascii_letters).lower()
.
.
.
z = random.choice(string.ascii_letters).lower()
alphabet =
{'a':a,'b':b,'c':c,'d':d,'e':e,'f':f,'g':g,'h':h,
'i':i,'j':j,'k':k,'l':l,'m':m,'n':n,
'o':o,'p':p,'q':q,'r':r,'s':s,'t':t,
'u':u,'v':v,'w':w,'x':x,'y':y,'z':z}
Upvotes: 1
Views: 751
Reputation: 1124080
Don't use separate choice()
calls. Use random.sample()
, picking from string.ascii_lowercase
rather than lowercasing:
# pick 10 random keys, all unique
keys = random.sample(string.ascii_lowercase, 10)
If all you are doing is shuffling all 26 letters, then use random.shuffle()
:
# list of 26 letters in random order
random_letters = list(string.ascii_lowercase)
random.shuffle(random_letters)
# map the alphabet to the random letters
alphabet = dict(zip(string.ascii_lowercase, random_letters))
Upvotes: 5