search

Home  >  Q&A  >  body text

python - Merge multiple lists into a dictionary

I have simplified the original question and hope you can help me a lot

There are 2 lists of equal length:
idlist = [id1,id2,id3,id4,id5]
userlist = [name1,name2,name3,name4,name5]

Hope to merge into a dictionary in the following form:

dict_user = {{'id':id1, 'name':name1},{'id':id2, 'name':name2},{'id':id3, 'name':name3},{' id':id4, 'name':name4},{'id':id5, 'name':name5}}

How to generate the above dictionary?

Supplement: python 3

ringa_leeringa_lee2712 days ago1116

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-06-28 09:24:02

    First of all, your dict_user does not look like a dictionary, but each element in it is a dictionary. You can use the zip function to merge two lists of equal length into a two-dimensional list. In python3, idlist = [id1, id2, id3, id4, id5]
    userlist = [name1,name2,name3,name4,name5]
    zipped= zip(idlist, userlist)
    user= [dict(id=id,name=name) for id ,name in list(zipped)]
    You can get
    user = [{'id':id1, 'name':name1},{'id':id2, 'name':name2},{'id':id3, 'name':name3},{' id':id4, 'name':name4},{'id':id5, 'name':name5}]

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-06-28 09:24:02

    for way

    var listObj={},dict_user=[];
    for(var i=0,len=idlist.length;i<len;i++){
        listObj.id=idlist[i]
        listObj.name=userlist[i]
        dict_user.push(listObj);
    }
    

    foeEach

    var listObj={},dict_user=[];
    idlist.forEach(function(item,index,self){
        listObj.id=item;//listObj.id=idlist[index];
        listObj.name=userlist[index];
        dict_user.push(listObj);
    })
    
    
    
    忽略吧!我看错了!
    

    reply
    0
  • PHP中文网

    PHP中文网2017-06-28 09:24:02

    First of all
    dict_user = { ... } This form should be a set (set/frozenset), but both of them require the stored object to be hashable, that is, it cannot be a variable object like dict, so there is no such thing form.

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-28 09:24:02

    should bedict_user = [{'id':id1, 'name':name1},{'id':id2, 'name':name2},{'id':id3, 'name':name3},{ 'id':id4, 'name':name4},{'id':id5, 'name':name5}]Well, if so, the code is as follows:

    dict_user = [{"id": id, "name": user} for id, user in zip(idlist, userlist)]

    reply
    0
  • Cancelreply