0

I'm trying to make this code so it prints out everything in the dictionary, and then the user can pick what dictionary item they want, I would need to be able to use the key they picked and remove it from the dictionary.

dict = {'i': [24062, 'txt'], 'e': [10293, 'txt2']}

v = 0
for i in dict
    v += 1
    print(f'({v}) {i}')
v += 1
print(f'({v}) Back')
getinput = int(input('>> '))
if getinput < v and getinput > -1:
# I want it to find the key and value you selected
# I want it to print the key and the value you selected
elif getinput == v:
    print('Go back to menu')
else:
    print('Didnt work :(')
ColoredHue
  • 59
  • 7
  • And also side note: bad idea to name your dictionary `dict` in general, as you are basically overwriting a already existing name in python. – Pac0 Apr 09 '22 at 17:28

2 Answers2

2

This approach creates another dictionary (container of key: value pairs) e with key equal to the index associated with a key from the d dictionary and with the value equal to the corresponding key from the d dictionary. Given your dictionary above (I am calling it d), e would be {0: 'i', 1: 'e'}: the values represent keys from the d dictionary and the keys are the indices of those keys from the d dictionary.

The user will then be selecting one of the indices. e[getinput] will then provide the associated key of the d dictionary.

I hope this helps. Please let me know if there are any questions!

d = {'i': [24062, 'txt'], 'e': [10293, 'txt2']}

e = {}
for idx, i in enumerate(d):
    e[idx] = i
    print(f'({idx}) {i}')

idx += 1
print(f'({idx}) back')

# get user input 
getinput = int(input('>> '))
if getinput <= idx - 1 and getinput >= 0:
    print(f"You selected: {e[getinput]}: {d[e[getinput]]}")
elif getinput == idx:
    print('Go back to menu')
else:
    print('Didnt work :(')

Example Session:

(0) i
(1) e
(2) back
>> 1
You selected: e: [10293, 'txt2']
OTheDev
  • 2,916
  • 2
  • 4
  • 20
1

Try this. You can convert the dictionary to list and get the key and value according to an index.

dict = {'i': [24062, 'txt'], 'e': [10293, 'txt2']}

v = 0
for i in dict:
    v += 1
    print(f'({v}) {i}')
v += 1
print(f'({v}) Back')
getinput = int(input('>> '))

index = getinput -1
if getinput < v and getinput > -1:
    key = list(dict)[index]
    val = list(dict.values())[index]
    print(key, val)

elif getinput == v:
    print('Go back to menu')
else:
    print('Didnt work :(')

Output:

E:\>python test.py
(1) i
(2) e
(3) Back
>> 1
i [24062, 'txt']

E:\>python test.py
(1) i
(2) e
(3) Back
>> 2
e [10293, 'txt2']

E:\>python test.py 3
(1) i
(2) e
(3) Back
>> 3
Go back to menu

This below question has further details. How to index into a dictionary?

Manjunath K Mayya
  • 1,078
  • 1
  • 11
  • 20