用相同的键将多个字典附加值

时间:2020-11-01 21:09:20

标签: python dictionary

我正在使用Python 3.9。我需要将具有列表值的多个字典合并到将数组值附加到每个键上

public class BASE64DecodedMultipartFile implements MultipartFile {
        private final byte[] imgContent;

        public BASE64DecodedMultipartFile(byte[] imgContent) {
            this.imgContent = imgContent;
        }

        @Override
        public String getName() {
            // TODO - implementation depends on your requirements 
            return null;
        }

        @Override
        public String getOriginalFilename() {
            // TODO - implementation depends on your requirements
            return null;
        }

        @Override
        public String getContentType() {
            // TODO - implementation depends on your requirements
            return null;
        }

        @Override
        public boolean isEmpty() {
            return imgContent == null || imgContent.length == 0;
        }

        @Override
        public long getSize() {
            return imgContent.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return imgContent;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(imgContent);
        }

        @Override
        public void transferTo(File dest) throws IOException, IllegalStateException { 
            new FileOutputStream(dest).write(imgContent);
        }
    }

结果应为:

        params: {
            new_value: 'value'
        },

1 个答案:

答案 0 :(得分:1)

您可以使用collections.defaultdict

from collections import defaultdict

input_dirs = [{'xx5.8.38': ['testingxyz-597247']},
              {'xx5.8.38': ['testingxyz-597624']},
              {'xx5.8.38': ['testingxyz-597626']},
              {'xx1.0.3': ['testingxyz-597247']},
              {'xx1.0.3': ['testingxyz-597624']},
              {'xx1.0.3': ['testingxyz-597626']}]


result_dir = defaultdict(list)
for single_dir in input_dirs:
    for key, val in single_dir.items():
        result_dir[key].extend(val)

给你

defaultdict(<class 'list'>,
            {'xx1.0.3': ['testingxyz-597247',
                         'testingxyz-597624',
                         'testingxyz-597626'],
             'xx5.8.38': ['testingxyz-597247',
                          'testingxyz-597624',
                          'testingxyz-597626']})