Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python词典列表问题_Python - Fatal编程技术网

Python词典列表问题

Python词典列表问题,python,Python,我对字典列表有以下输入: links = [ {'uid': 1, 'lid': 6, 'path': 'a1.txt', 'shareid': 1}, {'uid': 1, 'lid': 7, 'path': 'a2.txt', 'shareid': 2}, {'uid': 1, 'lid': 8, 'path': 'a1.txt', 'shareid': 1}] 我需要生成这个输出: op = {'a1.txt': {'shareid': 1, 'l

我对字典列表有以下输入:

    links = [ {'uid': 1, 'lid': 6, 'path': 'a1.txt', 'shareid': 1},
      {'uid': 1, 'lid': 7, 'path': 'a2.txt', 'shareid': 2},
      {'uid': 1, 'lid': 8, 'path': 'a1.txt', 'shareid': 1}]
我需要生成这个输出:

    op = {'a1.txt': {'shareid': 1, 'lid': [6, 8]},
          'a2.txt': {'shareid': 2, 'lid': [7]}
         }
下面是我编写的代码:

def list_all_links():
       new_list = []
       result = {}

       for i in range(len(links)):
           entry = links[i]

    if not result.has_key(entry['path']):
        new_entry = {}
        lid_list = []
        new_entry['shareid'] = entry['shareid']
        if new_entry.has_key('lid'):
            lid_list = new_entry['lid']
            lid_list.append(entry['lid'])
        else:
            lid_list.append(entry['lid'])
        new_entry['lid'] = lid_list

        result[entry['path']] = new_entry

    else:
        new_entry = result[entry['path']]
        lid_list = new_entry['lid']

        if new_entry.has_key(entry['shareid']):
            new_entry['shareid'] = entry['shareid']
            lid_list = new_entry['lid']
            lid_list.append(entry['lid'])
            new_entry['lid'] = lid_list


        else:
            new_entry['shareid'] = entry['shareid']
            lid_list.append(entry['lid'])
            new_entry['lid'] = lid_list


        result[entry['path']] = new_entry

print "result = %s" %result


if __name__ == '__main__':
    list_all_links()

我能够根据需要生成相同的输出。但是,有人能告诉我是否有更好的方法来解决这个问题吗?

虽然不是很好,但下面的解决方案很有效:

links = [ {'uid': 1, 'lid': 6, 'path': 'a1.txt', 'shareid': 1},
      {'uid': 1, 'lid': 7, 'path': 'a2.txt', 'shareid': 2},
      {'uid': 1, 'lid': 8, 'path': 'a1.txt', 'shareid': 1}]

links_restructured = [(d['path'], {'shareid': d['shareid'], 'lid': [d['lid']]}) for d in links]
answer = {}
for link in links_restructured:
    if link[0] not in answer:
        answer[link[0]] = link[1]
    else:
        answer[link[0]]['lid'].extend(link[1]['lid'])
print(answer)
输出

{'a2.txt': {'lid': [7], 'shareid': 2}, 'a1.txt': {'lid': [6, 8], 'shareid': 1}}
输出:
您可以使用
dict
setdefault
方法将其缩短

links = [
  {'uid': 1, 'lid': 6, 'path': 'a1.txt', 'shareid': 1},
  {'uid': 1, 'lid': 7, 'path': 'a2.txt', 'shareid': 2},
  {'uid': 1, 'lid': 8, 'path': 'a1.txt', 'shareid': 1}
]

op = dict()
for a in links:
  op.setdefault(a['path'], {}).update(shareid=a['shareid'])
  op[a['path']].setdefault('lid', []).append(a['lid'])
print op
输出:

{'a2.txt': {'lid': [7], 'shareid': 2}, 'a1.txt': {'lid': [6, 8], 'shareid': 1}}
我是这样做的:

def process_links(links):
    '''
       process entries in list 'links';
       returns dictionary 'op'
    '''
    op = {}
    for dict in links:
        op_key = dict['path']
        if op_key in op:
            pass
        else:
            op[op_key] = {'shareid':None, 'lid':[]}
    return op

def fill_op(op_dict, link_list):
    for dict in link_list:
        op_key = dict['path']
        # fill shareid
        op_dict[op_key]['shareid'] = dict['shareid']
        # fill lid
        lid_list = op_dict[op_key]['lid'] 
        lid_list.append(dict['lid'])
        op_dict[op_key]['lid'] = lid_list
    return op_dict


if __name__ == "__main__":
    links = [ {'uid': 1, 'lid': 6, 'path': 'a1.txt', 'shareid': 1},
              {'uid': 1, 'lid': 7, 'path': 'a2.txt', 'shareid': 2},
              {'uid': 1, 'lid': 8, 'path': 'a1.txt', 'shareid': 1}]
    result1 = process_links(links)
    result2 = fill_op(result1, links)
    print(result2)
输出略有不同:{'a1.txt':{'lid':[6,8],'sharedid':1},'a2.txt':{'lid':[7],'sharedid':2}

{'a2.txt': {'lid': [7], 'shareid': 2}, 'a1.txt': {'lid': [6, 8], 'shareid': 1}}
def process_links(links):
    '''
       process entries in list 'links';
       returns dictionary 'op'
    '''
    op = {}
    for dict in links:
        op_key = dict['path']
        if op_key in op:
            pass
        else:
            op[op_key] = {'shareid':None, 'lid':[]}
    return op

def fill_op(op_dict, link_list):
    for dict in link_list:
        op_key = dict['path']
        # fill shareid
        op_dict[op_key]['shareid'] = dict['shareid']
        # fill lid
        lid_list = op_dict[op_key]['lid'] 
        lid_list.append(dict['lid'])
        op_dict[op_key]['lid'] = lid_list
    return op_dict


if __name__ == "__main__":
    links = [ {'uid': 1, 'lid': 6, 'path': 'a1.txt', 'shareid': 1},
              {'uid': 1, 'lid': 7, 'path': 'a2.txt', 'shareid': 2},
              {'uid': 1, 'lid': 8, 'path': 'a1.txt', 'shareid': 1}]
    result1 = process_links(links)
    result2 = fill_op(result1, links)
    print(result2)