Max Chung
Max Chung

Reputation: 97

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?

Upvotes: 0

Views: 239

Answers (2)

Malcolm
Malcolm

Reputation: 315

You're on the same track I'd take - zipping lists together to create the 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.

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]

Upvotes: 0

flakes
flakes

Reputation: 23624

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.

Upvotes: 1

Related Questions