0

i want to see an output based on the dictionary with input values.

here's the code :

list_harga = {'private':100000,'group':50000}
list_harga


name = str(input('nama: '))
member = str(input('member: '))
tipe_kelas = str(input('kelas: '))

harga=[list_harga[x] for x in tipe_kelas]
harga

i encounter an error :

KeyError          Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_15824\2571049863.py in <module>
      8 print(tipe_kelas)
      9 
---> 10 harga=[list_harga[x] for x in tipe_kelas]
     11 harga

~\AppData\Local\Temp\ipykernel_15824\2571049863.py in <listcomp>(.0)
      8 print(tipe_kelas)
      9 
---> 10 harga=[list_harga[x] for x in tipe_kelas]
     11 harga

KeyError: 'g'

the expected output is, when tipe_kelas is private then it will come 100000.

am I missing something?

James Z
  • 12,209
  • 10
  • 24
  • 44
  • 1. `str(input(...))` is redundant. The output of `input` is already a string, so there is no need to convert it. 2. `for x in tipe_kelas` is looping over the letters in a string. You probably just want `harga=list_harga[tipe_kelas]`. 3. `list_harga` is actually a `dict`. Probably better to name it `dict_harga` – flakes Apr 06 '23 at 05:27
  • What are you hoping to achieve? – DarkKnight Apr 06 '23 at 08:30
  • Welcome to Stack Overflow. If you wanted `tipe_kelas` to have *multiple* values to look up in the dictionary, please see the linked duplicates for some guidance. `input` will **only ever give you a string**; you must write your own code to process that. If you expected a single word of input to look up, then it does not make any sense to use a list comprehension, or a `for` loop, or any other kind of iteration. You have one value to look up, so just do it. – Karl Knechtel Apr 06 '23 at 08:31
  • The question cannot properly be understood right now, because there are many possibilities for what you want (how the user should type the `tipe_kelas`, and what should happen as a result. However, no matter what you wanted, this is almost certainly a common question that has been asked many times before (or else that is the *underlying* question, or else you just have a typo or need to take a break and think more clearly). – Karl Knechtel Apr 06 '23 at 08:33

1 Answers1

0

Don't loop over the characters of tipe_kelas

Just use that whole variable as the key, to access the list_harga dictionary.

For example:

list_harga = {'private':100000,'group':50000}
list_harga


name = str(input('nama: '))
member = str(input('member: '))
tipe_kelas = str(input('kelas: '))

harga=list_harga[tipe_kelas]
print(harga)
ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26