简体   繁体   English

从具有固定键值的字符串列表创建多个字典

[英]Create multiple dictionaries from lists with strings with fixed key values

I have a list of user info like我有一个用户信息列表,例如

[name1,link1,id1,name2,link2,id2,name3,link3,id3,...]

And I want to output a list with multiple dictionaries inside like我想输出一个包含多个字典的列表,比如

[
 {"name":"name1",
  "link":"link1",
  "id":"id1"
 },
 {"name":"name2",
  "link":"link2",
  "id":"id2"
 },
 {"name":"name3",
  "link":"link3",
  "id":"id3"
 }
]

At first I tried this起初我试过这个

user_info_keys = ["name","link","id","name","link","id","name","link","id"]

user_info_value = ["name1","link1","id1","name2","link2","id2","name3","link3","id3"]

for keys,value in zip(user_info_keys,user_info_value):
    user_info_dict = dict(zip(user_info_keys,user_info_value))

But it only outputs但它只输出

{"name":"name3","link":"link3","id":"id3"}

How should I change to code to get the expected result?我应该如何更改代码以获得预期的结果?

I'd probably just go with a dead-brained approach and an index to get each section:我可能只是采用一种死脑筋的方法和一个索引来获取每个部分:

user_info_keys = ["name","link","id","name","link","id","name","link","id"]

user_info_value = ["name1","link1","id1","name2","link2","id2","name3","link3","id3"]

outputs = [
    dict(zip(user_info_keys[i:i+3], user_info_value[i:i+3]))
    for i in range(0, len(user_info_keys), 3)
]

Note that this will fail if there aren't exactly 3 keys for each dict.请注意,如果每个 dict 没有正好 3 个键,这将失败。

You're on the same track I'd take - zipping lists together to create the dicts.你在我想要的同一条轨道上 - 将列表压缩在一起以创建 dicts。

You just need to break up your list into chunks and do it to each chunk.你只需要把你的列表分成几块,然后对每个块做。

There's an example of a grouper function in the itertools docs that can be used for this. itertools 文档中有一个 grouper 函数的示例,可用于此目的。

from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

keys = ["name", "link", "id"]

user_info = ["name1","link1","id1","name2","link2","id2","name3","link3","id3"]

groups = grouper(user_info, n=len(keys), fillvalue='')

users = [dict(zip(keys, values)) for values in groups]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM