如何将给定列表的值放入现有字典中? [英] How to put values of a given List into a existing dictionary?

查看:323
本文介绍了如何将给定列表的值放入现有字典中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含其元素的列表

I've got a List with their elements

my_list = ['a', 'b', 'c']

和一个以键和空白字符串作为值的字典

and a Dictionary that has their keys and blank strings as their values

my_dictionary = {
    'key_a' : '',
    'key_b' : '',
    'key_c' : '',
}

问题是:将此列表中的每个元素(按此特定顺序)放置为这些字典值中的每个的pythonic方法是什么?

The question is: what is the pythonic way to put each one of this list's elements (in this particularly order) as each one of those dictionary values?

结果应如下所示:

my_dictionary = {
    'key_a' : 'a',
    'key_b' : 'b',
    'key_c' : 'c',
}

Ps:请注意,在复制后我不需要字典值.正如评论中指出的那样,在Python 3.7之后,不再保证字典的顺序

Ps: please note that I do not need the dictionary values to be in order after that copy. As well pointed in the comments, after Python 3.7, dictionary's order is not guaranteed anymore

推荐答案

您可以尝试一下.

dict(zip(my_dictionary,my_list))

使用.update方法更新您的my_dictionary.

输出

{'key_a': 'a', 'key_b': 'b', 'key_c': 'c'}

注意:这适用于python3.7或更高版本.

Note: This works for python3.7 or above.

@MisterMiyagi 的注释中说明了原因.

The reason is stated in the comments by @MisterMiyagi.

这篇关于如何将给定列表的值放入现有字典中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆