我如何减少字典列表

发布于 2025-01-27 20:12:07 字数 1490 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不离久伴 2025-02-03 20:12:07

您可以使用列表理解来执行此操作:

mynewlist = [{'a': item['a']} for item in mylist]

循环在列表上,只需从dict中获取a值即可。对于myNewlist2,只需做同样的事情,但是有2个值:

mynewlist2 = [{'a': item['a'], 'b': item['b']} for item in mylist]

You can use list comprehension to do this:

mynewlist = [{'a': item['a']} for item in mylist]

Loop over the list and just grab the a value from the dict. For mynewlist2, just do the same thing, but with 2 values:

mynewlist2 = [{'a': item['a'], 'b': item['b']} for item in mylist]
北城孤痞 2025-02-03 20:12:07

像以下内容应该解决问题。请注意,这只会保留trunc_size嵌套词典的数字。不是条目ab的特定特定条目。目前尚不清楚需要哪个,但是如果您的词典中的键更改,目前在这个问题上的两个答案都将产生不同的结果。

def truncate_nested_dicts(list_of_dicts, trunc_size):
    outlist = []
    outdict = {}
    for d in list_of_dicts:
        for k,v in list(d.items())[:trunc_size]:
            outdict[k]=v
        outlist.append(outdict)
        outdict={}
    return outlist

print(truncate_nested_dicts(mylist, 2)) 
>>>[{'a': 'x', 'b': 'y'}, {'a': 'e', 'b': 'f'}, {'a': 'h', 'b': 'i'}]

Something like the following should do the trick. Note that this just keeps the trunc_size number of nested dictionaries. Not specific to entries a and b. It's unclear which was needed, but both answers currently on this question will yield different results if your keys in your dictionaries change.

def truncate_nested_dicts(list_of_dicts, trunc_size):
    outlist = []
    outdict = {}
    for d in list_of_dicts:
        for k,v in list(d.items())[:trunc_size]:
            outdict[k]=v
        outlist.append(outdict)
        outdict={}
    return outlist

print(truncate_nested_dicts(mylist, 2)) 
>>>[{'a': 'x', 'b': 'y'}, {'a': 'e', 'b': 'f'}, {'a': 'h', 'b': 'i'}]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文