简体   繁体   中英

python check if dictionary value is made of list of strings

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)

>>> 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

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())

ie, "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.

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}
[isinstance(i, list) for i in user_input.values()] and [isinstance(i, str) for i in user_input.keys()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM