{/'title/':/'Python 字典转换:将嵌套字典转换为列表字典/',/'description/':/'本文介绍使用 Python 列表推导式将嵌套字典 image_mapping 转换为包含多个字典的列表,每个字典包含图像名称、格式和文件名。/',/'keywords/':/'python, 字典, 转换, 列表推导式, 嵌套字典, 列表字典, image_mapping/',/'content/':/'///'import pandas as pd////n////nimage_mapping = {////n 'image_1': {'psd': 'image_1.psd', 'jpg': 'image_1.jpg', 'png': 'image_1.png'},////n 'image_2': {'psd': 'image_2.psd', 'jpg': 'image_2.jpg', 'png': 'image_2.png'},////n 'image_3': {'psd': 'image_3.psd', 'jpg': 'image_3.jpg', 'png': 'image_3.png'},////n 'image_4': {'psd': 'image_4.psd', 'jpg': 'image_4.jpg', 'png': 'image_4.png'}////n}////n////ndata = []////n////nfor image_name, formats in image_mapping.items():////n for format_name, file_name in formats.items():////n data.append([image_name, format_name, file_name])////n////ndf = pd.DataFrame(data, columns=['Image Name', 'Format', 'File Name'])////n用什么方法将mage_mapping转换成这样////n[{////n//t///'Image Name///':image_1,///'Format///':///'psd///',///'File Name///':///'image_1.psd///'////n},////n{////n//t///'Image Name///':image_1,///'Format///':///'jpg///',///'File Name///':///'image_1.jpg///'////n}....////n////n///'内容:可以使用列表推导式来将image_mapping转换成所需的格式:////n////npython////nconverted_data = [{'Image Name': image_name, 'Format': format_name, 'File Name': file_name} ////n for image_name, formats in image_mapping.items() ////n for format_name, file_name in formats.items()]////n////nprint(converted_data)////n////n////n输出结果为:////n////npython////n[{'Image Name': 'image_1', 'Format': 'psd', 'File Name': 'image_1.psd'},////n {'Image Name': 'image_1', 'Format': 'jpg', 'File Name': 'image_1.jpg'},////n {'Image Name': 'image_1', 'Format': 'png', 'File Name': 'image_1.png'},////n {'Image Name': 'image_2', 'Format': 'psd', 'File Name': 'image_2.psd'},////n {'Image Name': 'image_2', 'Format': 'jpg', 'File Name': 'image_2.jpg'},////n {'Image Name': 'image_2', 'Format': 'png', 'File Name': 'image_2.png'},////n {'Image Name': 'image_3', 'Format': 'psd', 'File Name': 'image_3.psd'},////n {'Image Name': 'image_3', 'Format': 'jpg', 'File Name': 'image_3.jpg'},////n {'Image Name': 'image_3', 'Format': 'png', 'File Name': 'image_3.png'},////n {'Image Name': 'image_4', 'Format': 'psd', 'File Name': 'image_4.psd'},////n {'Image Name': 'image_4', 'Format': 'jpg', 'File Name': 'image_4.jpg'},////n {'Image Name': 'image_4', 'Format': 'png', 'File Name': 'image_4.png'}]////n///'}/

Python 字典转换:将嵌套字典转换为列表字典

原文地址: https://www.cveoy.top/t/topic/p1X1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录