Alessio Colizza Alessio Colizza - 3 months ago 13
Python Question

Need to print the values of a dictionary by calling the keys within a range

I made a dictionary with

key = integer
value = string


I would like to make an .exe (probably it's a bit early for my level) where I can input 2 integers and it would print the values of the keys within the range I specified.

eg.

{1: 'General 001-002', 3: 'Computer science', 7: 'Bibliography', 20: 'Library & Information', 30: 'General 030-068', 69: 'Museum Science', 70: 'Journalism & News Media', 80: 'General 080-099', 100: 'Philosophy 100-149', 150: 'Psychology',}


I'd like to input 5 and 85 and want it to print

Bibliography
Library & Information
General 030-068
Museum Science
Journalism & News Media
General 080-099


EDIT:

Thank you all for the suggestions.

My code looks like this right now and is working as it should:

text_file = open("dewey.txt", "rt") #Open the list containing the values

text = text_file.read().split('\n')
text_file.close()


num = []
with open ('dewey num.txt', 'rt') as in_file: #Open the list containing the keys
for line in in_file:
num.append(line[:3])
intenum = []
for i in num:
intenum.append(int(i)) #Make the keys as integers


dict1= dict(zip(intenum,text)) #Merge the 2 lists in a dictionary
print ('This software will give you the subjects for each stack.') #Instructions for the user
print ('I need to know the range first, please only use the first three numbers of the classmark.') #Instructions for the user

x=input('Please key in the starting number for this stack: ') #Input for start
y=input('Please key in the last number for this stack: ') #Input for stop

start = int(x)
stop = int(y)

values = [dict1[k] for k in range(start, stop + 1) if k in dict1] #Call the values in range
print('The subject(s) for this section: ')
for i in values: #Print the values in range
print (i)


My next step is to make it an .exe so I'm studying py2exe, pyinstaller and cx_freeze. If you have any insight on what's better for my script it would be much appreciated.

I'm using Python 3.5.2

Alessio

Answer

The solution is quite short:

# this is your dictionary
d = {1: 'General 001-002', 3: 'Computer science', 7: .....}

start = 5
stop = 85

values = [d[k] for k in range(start, stop + 1) if k in d]

You get what you need in values - a list.

I omitted most of the dictionary, but it's stored in d.

I used a list comprehension, taking the dictionary value at the key k for k running in the range (stop + 1 because range reaches to end of the range minus 1) provided that k is within the key values.

The expression

k in d

tests whether the key k is in the keys of the dict d, and it's the same as testing:

k in d.keys()
Comments