[英]Checking if a key exists and its value is not an empty string in a Python dictionary
[英]Verify string exists as key or value in Python dictionary?
我正在为linux目录构建一个scraper / crawler。 从本质上讲,该程序将采取用户输入的文件类型来刮(这是我的问题来自哪里)
我将可接受的文件扩展名类型存储在具有嵌套列表的字典中,例如:
file_types = {'images': ['png', 'jpg', 'jpeg', 'gif', 'bmp'], 'text': ['txt', 'doc', 'pdf']}
为了给用户提供他们必须选择的选项,我使用for for循环:
for k, v in file_types.items():
print(k, v)
以这种格式打印字典:
audio ['mp3', 'mpa', 'wpi', 'wav', 'wpi']
text ['txt', 'doc', 'pdf']
video ['mp4', 'avi', '3g2', '3gp', 'mkv', 'm4v', 'mov', 'mpg', 'wmv', 'flv']
images ['png', 'jpg', 'jpeg', 'gif', 'bmp']
如果我这样做:
scrape_for = input("Please enter either the type of file, or the extension you would like to scrape for: \\n")
如何验证我的字典file_types
存在的用户输入是一个键还是一个值(我说键OR值,所以如果用户输入'images'我可以使用关键图像的值)
我首先将扩展列表展平为一个集合,以便您以后不必循环遍历它,并且可以快速进行现场查找:
file_types = {'images': ['png', 'jpg', 'jpeg', 'gif', 'bmp'], 'text': ['txt', 'doc', 'pdf']}
file_extensions = set(sum(file_types.values(), []))
scrape_for = input("Enter the type / extension to scrape: ").lower()
if scrape_for not in file_types and scrape_for not in file_extensions:
print("I don't support this type / extension!")
使用Python的酷列表理解可以得到一个扩展列表
list_of_extensions = [ item \
for extensionList in file_types.values() \
for item in extensionList
]
现在使用Python的成语结构item in list_var
,其计算结果为真,如果该项目是目前在该列表中,和or
。
if scrape_for in file_types or scrape_for in list_of_extensions:
# do something
else:
print("Unsupported file type: " + scrape_for)
注意:在dict名称上使用in
运算符与scrape_for in file_types.keys()
等效(实际上scrape_for in file_types.keys()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.