Python Forum
How to make this dictionary-generating code more efficient?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to make this dictionary-generating code more efficient?
#1
My code below works. I used a second variable (count) to generate the dictionary. How could I have done this more efficiently?

import random
str = "abcdefg"
print()
print(' This program randomly generates a cipher dictionary from the string',str,end="")
print('.')
print(' Cipher dictionary is:')

def make_cipher_dict(str):
    CIPHER_DICT = {}
    lst = list(str)
    sndlst = list(str)
    random.shuffle(sndlst) #random method changes specified list rather than creating new list
#    print(lst)  DEBUG
#    print(sndlst)  DEBUG
#    quit()  DEBUG
    count = 0
    for a in lst:
        CIPHER_DICT[a] = sndlst[count]
        count = count + 1
    print("",CIPHER_DICT)
    return;

make_cipher_dict(str)
Reply
#2
Don't name variables str. There is a built-in function named str, and naming your variable str blocks access to it.

As to efficiency, get rid of count. You're not using it for anything, why are you calculating it? Have you learned zip yet? If so, it can be used to efficiently make a dictionary. The dictionary docs have examples.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Delete line 9 (if you do the rest below)
Delete lines 13-16
Change 17 to
cipher_dict = {a:b for (a,b) in zip(sndlst,str)}
though I agree with not using str as a variable.
Delete 18-20, move the print statement to after line 23 (style issue - your function is called make_cipher_dict, not print it, so would change 21 to return the dictionary and print it from the main program. That makes the function much more re-usable)
Reply
#4
I'm not sure a dict comprehension is more efficient than the dict constructor that I was talking about.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] help me make this code better please (basic) Rustam 2 2,228 Jun-19-2020, 01:27 PM
Last Post: Rustam
  John Guttag Book - Finger Exercise 4 - need help to make the code better pritesh 12 10,523 May-06-2020, 05:10 PM
Last Post: riteshp
  Creating code to make up to 4 turtle move simultaneously in a random heading J0k3r 3 5,408 Mar-05-2018, 03:48 PM
Last Post: mpd
  How to make faster this code Ace 1 2,928 Oct-23-2017, 12:11 PM
Last Post: Larz60+
  How can I make faster that code BlueEva00 1 2,656 Oct-18-2017, 03:51 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020