拆分列表python 3中的字典

问题描述 投票:0回答:3

我在列表中有一本字典

[{'123': 'some text'}]

我希望我的输出是一个字符串,键和值分开,就像这样

'123', 'some text'

有什么建议?

python-3.x
3个回答
0
投票

试试这个:

my_list_dict = [{'123': 'some text'}]

for elem in my_list_dict:
    for key in elem:
        print('key:', key)
        print('value:', elem[key])

0
投票

我想你想把这些价值列入清单吧?这是我的方法


    list_dict = [{'123': 'some text'}]
    list_without_dict = []
    for dict in list_dict:
      for key in dict:
        list_without_dict.append(key)
        list_without_dict.append(dict[key])

    print(list_without_dict)


0
投票

简单地遍历整个输入,保持键和值,并使用', '.join()将列表连接到一个字符串,其中“,”作为分隔符

wierd_input = [{'123': 'some text', 'foo':'boo'}, {'and':'another'}]

all_parts = []
for dictionary in wierd_input:
    for key, value in dictionary.items():
        all_parts.extend((key, value))

print(", ".join(all_parts))

>>123, some text, foo, boo, and, another

如果要在代码中频繁地加入这些对象,可以将其转换为生成器

def iterate_over_wierd(wierd):
    for dictionary in wierd:
        for key, value in dictionary.items():
            yield key
            yield value

print(", ".join(iterate_over_wierd(wierd_input)))

如果你迫切需要一个单行程,你可以使用itertools

import itertools
', '.join(itertools.chain.from_iterable(itertools.chain.from_iterable(map(dict.items,wierd_input))))

但我建议反对这个,因为一个班轮非常混乱和hacky,更好地坚持前两个

© www.soinside.com 2019 - 2024. All rights reserved.