1

Given the variable user_input = {'string': ['a', 'b', 'c']}

how to check that the variable type is dict(str: list)

isinstance() can only check if its a dictionary such as isinstance(user_input, dict)

systemshift
  • 11
  • 1
  • 3
  • 1
    There is new functionality in Python for type checking called Mypy, are you allowed to use that? Otherwise, perhaps you could loop over `user_input.values()` and test with `isinstance`? – mgrollins Nov 21 '19 at 23:47

4 Answers4

1
>>> all(isinstance(v, list) for v in user_input.values())
True
>>> all(isinstance(v, str) for v in user_input.keys())
True

all(isinstance(v, list) for v in user_input.values()) tests whether all the values are list all(isinstance(v, str) for v in user_input.keys()) tests whether all the values are str

Chao Peng
  • 179
  • 8
  • It may be worth noting here that ```all(isinstance(v, list) for v in user_input.values())``` and ```all(isinstance(v, str) for v in user_input.keys())``` would return ```True``` for an empty dictionary as well. – bglbrt Nov 21 '19 at 23:55
  • @Tibbles. Correct, and it should – Mad Physicist Nov 22 '19 at 00:34
1

You can't do it concisely, because (at runtime) there's no such thing as the type Dict[str, List[str]] (which is how you write out the type using Python's type hints). A dict is a dict is a dict, and it can hold keys and values of any type.

You can dig through the values and do the check yourself:

check = all(all(isinstance(v, str) for v in value) for value in user_input.values())

i.e., "all of the values in all of the lists inside the dictionary are strings". But as you can see, this is hardly elegant. If this is indeed user input, it would be better to check types as the input comes in, before you ever put it in the dictionary. However, I should also note that input always returns strings, so you may not even need to do this check.

Josh Karpel
  • 2,110
  • 2
  • 10
  • 21
0

You can make sure that you're looking at a dictionary by using:

type(user_input)

Now, if you want to make sure that all keys are strings, you can look at:

set(type(x) for x in user_input.keys())

The same goes for if you want to make sure that all values in the dictionary are lists:

set(type(x) for x in user_input.values())

So a one-liner way to do the check would be:

set(type(x) for x in user_input.keys()) == {str} and set(type(x) for x in user_input.values()) == {list}
bglbrt
  • 2,018
  • 8
  • 21
  • Generally, it's preferred to use `isinstance` rather than `type` for these kinds of checks https://stackoverflow.com/questions/1549801/what-are-the-differences-between-type-and-isinstance – snakecharmerb Nov 22 '19 at 04:45
0
[isinstance(i, list) for i in user_input.values()] and [isinstance(i, str) for i in user_input.keys()]
seralouk
  • 30,938
  • 9
  • 118
  • 133