来自四个不同列表的Python词典列表

时间:2018-02-09 00:23:54

标签: python list dictionary

有人可以帮我创建Python中的词典列表。

我想将以下列表转换为Python中的词典列表。

        value1 = ['name1', 'name2', 'name3', 'name4']
        value2 = ['6.0',  '8.5', '7.0', '9.5']
        value3 = [500, 600, 900, 750]
        value4 = ['$$','$$$','$', '$$']


        keys = ['name', 'rate', 'rev', 'amount']

The output list of dictionaries should look like this:

  [ {'name':'name1', 'rate':'6.0', 'rev':500, 'amount':'$$'},  
    {'name':'name2', 'rate':'8.5', 'rev':600, 'amount':'$$$'},  
    {'name':'name3', 'rate':'7.0', 'rev':900, 'amount':'$'},  
    {'name':'name4', 'rate':'9.5', 'rev':750, 'amount':'$$'} ]

Thanks.

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

value1 = ['name1', 'name2', 'name3', 'name4']
value2 = ['6.0',  '8.5', '7.0', '9.5']
value3 = [500, 600, 900, 750]
value4 = ['$$','$$$','$', '$$']
results = [dict(zip(['name', 'rate', 'rev', 'amount'], i)) for i in zip(*[value1, value2, value3, value4])]

输出:

[{'amount': '$$', 'rate': '6.0', 'rev': 500, 'name': 'name1'}, {'amount': '$$$', 'rate': '8.5', 'rev': 600, 'name': 'name2'}, {'amount': '$', 'rate': '7.0', 'rev': 900, 'name': 'name3'}, {'amount': '$$', 'rate': '9.5', 'rev': 750, 'name': 'name4'}]

答案 1 :(得分:0)

使用列表理解,像这样

    /**
 * @Route("/mon-espace/{id}/edit", name="edit")
 * @param Request $request
 * @param User $user
 * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
 */
public function editAction(Request $request, User $user)
{
    $editForm = $this->createForm(UserType::class, $user);
    /*        dump($user);die();*/
    $editForm->handleRequest($request);

    if ($editForm->isSubmitted() && $editForm->isValid())
    {
        $file = $user->getAttachment();
            $fileName = md5(uniqid()).'.'.$file->guessExtension();
            $file->move($this->getParameter('attachment_directory'), $fileName);
            $user->setAttachment($fileName);

        $this->getDoctrine()->getManager()->flush();
        return $this->redirectToRoute('monEspace',array('user'=> $user->getId()));
    }

    return $this->render('@User/profil/edit.html.twig' , array(
        'user'=> $user,
        'editForm' => $editForm->createView()
    ));
}

这为您提供了词典列表:

value1 = ['name1', 'name2', 'name3', 'name4']
value2 = ['6.0',  '8.5', '7.0', '9.5']
value3 = [500, 600, 900, 750]
value4 = ['$$','$$$','$', '$$']


results = [{'name':name, 'rate':rate, 'rev':rev, 'amount':amount} for name, rate, rev, amount in zip(value1, value2, value3, value4)]

我们可以使用[{'amount': '$$', 'name': 'name1', 'rate': '6.0', 'rev': 500}, {'amount': '$$$', 'name': 'name2', 'rate': '8.5', 'rev': 600}, {'amount': '$', 'name': 'name3', 'rate': '7.0', 'rev': 900}, {'amount': '$$', 'name': 'name4', 'rate': '9.5', 'rev': 750}] 一次从zipvalue1value2value3中获取一个值,并将其输入到每个字典中名单。然后,我们使用列表推导来迭代这个列表对象。