开发者

Python: dictionary and list manipulation help~

开发者 https://www.devze.com 2023-02-05 10:27 出处:网络
I have an initialed dictionary list list_dic = [{\'number\': 1}, {\'number\': 2}] I also got a list of other objects, here just use int to represent

I have an initialed dictionary list

list_dic = [{'number': 1}, {'number': 2}]

I also got a list of other objects, here just use int to represent

another_list = [2,3,4]

I want the result to be like this:

list_dic = [{'number': 1, 2: None, 3: None, 4: None},  \
{'number': 2, 2: None, 3: None, 4: N开发者_StackOverflowone}]

Try use the least code to do so, thanks very much.


Can't imagine why you'd want that, but here you go:

for dic in list_dic:
    dic.update(dict.fromkeys(another_list))


You answered it yourself:

use the list as keys to create a default dictionary, and then update the old one.

list_dic = [{'number': 1}, {'number': 2}]
another_list = [2,3,4]

for x in list_dic:
  x.update(dict.fromkeys(another_list))

print list_dic

Note how the for loop corresponds exactly with what you said; I think you just didn't know the correct names to use. Usually the docs help in that case.


[dic for dic in list_dic if dic.update(dict.fromkeys(another_list)) or True]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号