Python字典-如果键相同,则创建一个对应值列表字符串数据类型

问题描述

我的数据类型如下:

{'name': 'brian','location': 'brookings,OR'}
{'name': 'brian','location': 'Medford,OR'}
{'name': 'tommy','location': 'Portland,'location': 'Oklahoma City,OK'}

我想做的是,如果键(名称)相同,那么我将创建一个对应值的列表,如下所示:

{'name': 'brian','location': ['brookings,OR','Medford,OR']}
{'name': 'tommy','location': ['Portland,'Oklahoma City,OK']}

我通过将值加在一起来完成整数数据类型的操作,因为键是相同的,但是我对此一无所知。任何帮助表示赞赏。

解决方法

将包含您的词典的列表视为l:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="table-responsive">
<table id="table1" class="display">
  <thead>
    <tr>
      <th>Sr No.</th>  
      <th>Timestamp</th>
      <th>Email Id</th>
      <th>Whatsapp No</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
  <tr>
  <td class="sorting_1">1</td>
  <td>2020-10-29 20:53:23</td>
  <td>[email protected]</td>
  <td>+916302930342</td>
  <td>Lunavath Kapil</td>
  </tr>
  <tr>
  <td class="sorting_1">2</td>
  <td>2020-10-29 11:49:02</td>
  <td>[email protected]</td>
  <td>+916302930342</td>
  <td>Lunavath Kapil</td>
  </tr>
  <tr>
  <td class="sorting_1">3</td>
  <td>2020-10-27 00:47:35</td>
  <td>[email protected]</td>
  <td>+917227860350</td>
  <td>Hemali Bhadeshiya</td>
  </tr>
  <tr>
  <td class="sorting_1">10</td>
  <td>2020-10-26 13:52:39</td>
  <td>[email protected]</td>
  <td>+919780818089</td>
  <td>Veerpal kaur</td>
  </tr>
  </tbody>
</table>
</div>

您可以执行以下操作:

l=[{'name': 'brian','location': 'Brookings,OR'},{'name': 'brian','location': 'Medford,{'name': 'tommy','location': 'Portland,'location': 'Oklahoma City,OK'}]

输出:

res=[{'name':i,'location':[k['location'] for k in l if k['name']==i]} for i in set([p['name'] for p in l])]