首页 > 解决方案 > 如何更新字典列表中的每个字典

问题描述

我有一本看起来像这样的字典

[
    {'name': 'Apple', 'weight': 500, 'description': 'Apple is one of the most nutritious and healthiest fruits. It is very rich in antioxidants and dietary fiber. Moderate consumption can not only increase satiety, but also help promote bowel movements. Apple also contains minerals such as calcium and magnesium, which can help prevent and delay bone loss and maintain bone health. It is good for young and old.'},
    {'name': 'Avocado', 'weight': 200, 'description': 'Avocado contains large amount of oleic acid, a type of monounsaturated fat that can replace saturated fat in the diet, which is very effective in reducing cholesterol levels. Avocado is also high in fiber. Its soluble fiber can remove excess cholesterol from the body, while its insoluble fiber helps keep the digestive system functioning and prevent constipation.'},
    {'name': 'Blackberry', 'weight': 150, 'description': 'Blackberries have high nutritional value and are excellent fruit for health. It is rich in nutrients, various amino acids and trace elements necessary for the human body. They are good at promoting blood coagulation, delaying aging, improving immunity and reducing blood pressure and blood lipids. Blackberries can be consumed directly as fruit or made into jam and fruit wine.'},
    {'name': 'Grape', 'weight': 200, 'description': 'Grapes have up to 30% of sugar. A large amount of fruit acid in grapes helps digestion. Eating proper amount of grapes can strengthen the spleen and stomach. Grapes also contain the minerals calcium, potassium, phosphorus, iron, glucose, fructose, protein, tartaric acid, and various vitamins, which have strong nutritional functions and improve the function of the human body.'},
    {'name': 'Kiwifruit', 'weight': 250, 'description': 'Kiwifruit contains rich vitamin C, which can strengthen the immune system and supplement the nutrients consumed by the brain. Its perfect ratio of low sodium and high potassium can replenish the energy lost by working long hours.'},
    {'name': 'Lemon', 'weight': 300, 'description': 'Lemon is rich in vitamin C, which can improve immunity, accelerate wound healing and prevent colds. In the long run, it can lower the chance of developing cancer. Lemon juice helps reduce the burden on the digestive system and promotes the release of toxins from the body.'},
    {'name': 'Mango', 'weight': 300, 'description': 'Mango contains higher levels of vitamin C than ordinary fruits. Eating mango can also reduce cholesterol and triglycerides, and help prevent cardiovascular disease. Due to its high level of vitamins, regular consumption of mango play an important role in improving body function and moisturizing the skin.'},
    {'name': 'Plum', 'weight': 150, 'description': 'Plums are rich in sugar, vitamins, fruit acids, amino acids and other nutrients. With high nutritional value, Plums have outstanding health-care functions, which includes refreshing and nourishing liver, relieving depression and poisoning, and clearing dampness and heat of the human body.'},
    {'name': 'Strawberry', 'weight': 240, 'description': 'Strawberries are rich in carotene and vitamin A, which can alleviate night blindness, maintain the health of epithelial tissues, nourish the liver, and promote body growth and development. Strawberries contains large amount of dietary fiber as well, which can promote gastrointestinal motility and food digestion in the gastrointestinal tract.'},
    {'name': 'Watermelon', 'weight': 500, 'description': 'Watermelon is good for relieving heat, eliminating annoyance and quenching thirst. It contains a lot of water, which is good for relieving the symptoms of acute fever immediately. The sugar and salt contained in watermelon can diuretic and eliminate kidney inflammation. Watermelon also contains substances that can lower blood pressure.'}
]

我想要做的是更新该列表中的每个字典,键是 image_name,值是os.listdir(directory). 当我尝试这样做时:

for a_dict in list_of_dictionary:
    for image in os.listdir(dir_image):
        a_dict.update(image_name = image)

结果是这样的:

[
    {'name': 'Apple', 'weight': 500, 'description': 'Apple is one of the most nutritious and healthiest fruits. It is very rich in antioxidants and dietary fiber. Moderate consumption can not only increase satiety, but also help promote bowel movements. Apple also contains minerals such as calcium and magnesium, which can help prevent and delay bone loss and maintain bone health. It is good for young and old.', 'image_name': '010.txt'},
    {'name': 'Avocado', 'weight': 200, 'description': 'Avocado contains large amount of oleic acid, a type of monounsaturated fat that can replace saturated fat in the diet, which is very effective in reducing cholesterol levels. Avocado is also high in fiber. Its soluble fiber can remove excess cholesterol from the body, while its insoluble fiber helps keep the digestive system functioning and prevent constipation.', 'image_name': '010.txt'},
    {'name': 'Blackberry', 'weight': 150, 'description': 'Blackberries have high nutritional value and are excellent fruit for health. It’s rich in nutrients, various amino acids and trace elements necessary for the human body. They are good at promoting blood coagulation, delaying aging, improving immunity and reducing blood pressure and blood lipids. Blackberries can be consumed directly as fruit or made into jam and fruit wine.', 'image_name': '010.txt'},
    {'name': 'Grape', 'weight': 200, 'description': 'Grapes have up to 30% of sugar. A large amount of fruit acid in grapes helps digestion. Eating proper amount of grapes can strengthen the spleen and stomach. Grapes also contain the minerals calcium, potassium, phosphorus, iron, glucose, fructose, protein, tartaric acid, and various vitamins, which have strong nutritional functions and improve the function of the human body.', 'image_name': '010.txt'},
    {'name': 'Kiwifruit', 'weight': 250, 'description': 'Kiwifruit contains rich vitamin C, which can strengthen the immune system and supplement the nutrients consumed by the brain. Its perfect ratio of low sodium and high potassium can replenish the energy lost by working long hours.', 'image_name': '010.txt'},
    {'name': 'Lemon', 'weight': 300, 'description': 'Lemon is rich in vitamin C, which can improve immunity, accelerate wound healing and prevent colds. In the long run, it can lower the chance of developing cancer. Lemon juice helps reduce the burden on the digestive system and promotes the release of toxins from the body.', 'image_name': '010.txt'},
    {'name': 'Mango', 'weight': 300, 'description': 'Mango contains higher levels of vitamin C than ordinary fruits. Eating mango can also reduce cholesterol and triglycerides, and help prevent cardiovascular disease. Due to its high level of vitamins, regular consumption of mango play an important role in improving body function and moisturizing the skin.', 'image_name': '010.txt'},
    {'name': 'Plum', 'weight': 150, 'description': 'Plums are rich in sugar, vitamins, fruit acids, amino acids and other nutrients. With high nutritional value, Plums have outstanding health-care functions, which includes refreshing and nourishing liver, relieving depression and poisoning, and clearing dampness and heat of the human body.', 'image_name': '010.txt'},
    {'name': 'Strawberry', 'weight': 240, 'description': 'Strawberries are rich in carotene and vitamin A, which can alleviate night blindness, maintain the health of epithelial tissues, nourish the liver, and promote body growth and development. Strawberries contains large amount of dietary fiber as well, which can promote gastrointestinal motility and food digestion in the gastrointestinal tract.', 'image_name': '010.txt'},
    {'name': 'Watermelon', 'weight': 500, 'description': 'Watermelon is good for relieving heat, eliminating annoyance and quenching thirst. It contains a lot of water, which is good for relieving the symptoms of acute fever immediately. The sugar and salt contained in watermelon can diuretic and eliminate kidney inflammation. Watermelon also contains substances that can lower blood pressure.', 'image_name': '010.txt'}
]

如何使 image_name 的值为 001、002、...、010 而不仅仅是 010?

标签: python

解决方案


您需要创建一个列表并附加到它。目前,您只是用最后一个值覆盖。

for a_dict in list_of_dictionary:
    for image in os.listdir(dir_image):
        if 'image_name' in a_dict:
            a_dict['image_name'].append(image)
        else:
            a_dict['image_name']= [image]

您可以使用setdefault摆脱if-else阻塞:

for a_dict in list_of_dictionary:
    for image in os.listdir(dir_image):
        a_dict.setdefault('image_name', []).append(image)

更新:您可以使用zip()所需的输出,但您需要确保图像的数量和字典元素是相同的:

images = [for image in os.listdir(dir_image)]
for a_dict, image in zip(list_of_dictionary, images):
    a_dict.update('image_name' = image)

推荐阅读