1

I have a dictionary as follows:

details={'fname':'ankur',
    'lname':'sharma',
    'age':29,
    'skills':['HTML','CSS','Javascript','C','C++','Java'],
    'language':['Hindi','English','French'],
    'salary':50000
}

Now, if the user enters a value, and the value is in the dictionary, then I want to find key of that value. The following code doesn't work:

n=input('Enter value: ')
    
for i in details:
   if n in details[i]:
      print(details[i])

Suppose the user enters CSS, then the I want print the key of that value, i.e., skills. However, my code gives the following error:

Traceback (most recent call last):
  File "main.py", line 11, in <module>
    if n in details[i]:
TypeError: argument of type 'int' is not iterable
Dinux
  • 644
  • 1
  • 6
  • 19
  • 2
    The problem is that you want that user input is either value or member of/contained in a value. But you have mixed type values, e.g. you cannot test for membership in int (`'css' in 29`). You need to handle that differently. – buran May 11 '23 at 08:04
  • 1
    If you just want to judge "contains", just edit `if n in details[i]` to `if n in str(details[i])` – 911 May 11 '23 at 08:26
  • 1
    Do you need to be able to look up both integer and string values? – DarkKnight May 11 '23 at 08:32
  • I think the question should be clarified in order for you to get correct answers. What should the expected result be? Based on the example code, it looks like any dictionary value that contains the given search term should be printed. On the other hand, the description `now i want to find key on the basis of user input` would hint at finding the dictionary key(s) whose value contains the search term. Also, with the example search term of `css`, is the value for the dictionary key `skills`, the entire list, expected to be printed? That would mean that the search should be case-insensitive. – Jarno Lamberg May 11 '23 at 09:29

4 Answers4

0

You are getting an error because you are trying to iterate over an integer. You can use the following code for your purpose:

details={'fname':'ankur',
    'lname':'sharma',
    'age':29,
    'skills':['HTML','CSS','Javascript','C','C++','Java'],
    'language':['Hindi','English','French'],
    'salary':50000
}

n=input('Enter value: ')

for i in details:    
    if isinstance(details[i],list):
       if n in details[i]:
           print(i)
           break

    else:
        if n == str(details[i]):
            print(i)
            break

In the above code, we first check if a certain value in the dictionary is a list. If it is a list, and n is in that list, then we print the key of that list.

If a value in the dictionary is not a list, then we directly check if n equals that value; if it does, we print the key.

Dinux
  • 644
  • 1
  • 6
  • 19
0

I think your problem is that you are using in with a int. I'm not sure what you want to do about that but these are a few options:

Stop the iteration and move on:

for i in details:
    try:
        if n in details[i]:
            print(details)
    except:
        continue

Check for type:

for i in details:
   if isinstance(details[i], list):
       if n in details[i]:
          print(details)

If for strings and integers you want to check if the string matches them (not if they contain the string), you could do:

for i in details:
   if isinstance(details[i], list):
       if n in details[i]:
          print(details)
   else:
       if n == str(details[i]):
           print(details)

I'm not sure if you want to print the key or the value, but your question said print the key, so that's what I put.

N.B. Instead of iterating over details's keys, you could instead iterate over its keys and values:

for k, v in details.items():
    ...

Full code:

details={'fname':'ankur',
    'lname':'sharma',
    'age':29,
    'skills':['HTML','CSS','Javascript','C','C++','Java'],
    'language':['Hindi','English','French'],
    'salary':50000
}

n=input('Enter Value:')

for k, v in details.items():
   if isinstance(v, list):
       if n in v:
          print(k)
   else:
       if n == str(v):
           print(k)
sbottingota
  • 533
  • 1
  • 3
  • 18
  • Ok, the method using `details.items()` works. However, the `for i in details: ... if n == str(details[i]): print(details)` doesn't work. – Dinux May 11 '23 at 08:58
0

This error is because of you are try to iterate an integer as a string in your dictionary value. You can use this,

def get_key(data):
    for key,value in details.items():
        if isinstance(value,list):
            print(value)
            if data in value:
                return key
        if data in str(value):
            return key
    return None


n=input('Enter Value:')
print(get_key(n))

output is,

skills
Berlin Benilo
  • 472
  • 1
  • 12
0

Your values are either string, integer or list. You could take the user input and try to convert to int so that you have both the string and integer versions of the input. Then:

details = {
    'fname': 'ankur',
    'lname': 'sharma',
    'age': 29,
    'skills': ['HTML', 'CSS', 'Javascript', 'C', 'C++', 'Java'],
    'language': ['Hindi', 'English', 'French'],
    'salary': 50000
}

while ns := input('Enter Value: '):
    try:
        ni = int(ns)
    except ValueError:
        ni = None
    for k, v in details.items():
        if isinstance(v, list):
            if ns in v or (ni is not None and ni in v):
                print(k)
                break
        elif v == ni or v == ns:
            print(k)
            break
    else:
        print('Not found')

Console:

Enter Value: C++
skills
Enter Value: sharma
lname
Enter Value: 29
age
Enter Value:
DarkKnight
  • 19,739
  • 3
  • 6
  • 22