从字典 - Python创建前n个值(和键)的新dict

时间:2017-08-25 01:24:02

标签: python dictionary

我有一本字典:

{'my_account': [45010045, 43527907, 45147474, 35108100, 45159973],
 'your_account': [38966628, 28171579, 39573751, 41359842, 42445236],
 'his_account': [44822460, 45010045, 39276850, 39896128, 45265335]
}

我想保留每个键的前2个元素,因此结果如下:

{'my_account': [45010045, 43527907],
 'your_account': [38966628, 28171579],
 'his_account': [44822460, 45010045]
}

有没有办法实现这个目标?感谢。

2 个答案:

答案 0 :(得分:1)

使用字典理解

my_dict = {'my_account': [45010045, 43527907, 45147474, 35108100, 45159973],
 'your_account': [38966628, 28171579, 39573751, 41359842, 42445236],
 'his_account': [44822460, 45010045, 39276850, 39896128, 45265335]
}

new_dict = {k:v[:2] for k,v in my_dict.items()}
# {'my_account': [45010045, 43527907], 'your_account': [38966628, 28171579], 'his_account': [44822460, 45010045]}

答案 1 :(得分:0)

只需切片删除值。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="resultTable">
  <tr>
    <th>Question</th>
    <th>Decision</th>
    <th>Whose Decision</th>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>
相关问题