gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:51:30 25 4
gpt4 key购买 nike

我有一本字典:

{'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]
}

有什么办法可以实现这一点吗?谢谢。

最佳答案

使用字典理解

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]}

关于python - 从字典中创建前 n 个值(和键)的新字典 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45873086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com