【问题标题】:How to assign the values for dict(keys and values) into a new list? and also how to print the keys and values in the string dictionary?如何将 dict(键和值)的值分配到新列表中?以及如何打印字符串字典中的键和值?
【发布时间】:2018-08-03 03:35:21
【问题描述】:

我想打印一串字典的键和值。例如,

a = [{'1': '0'}, {'9': '2'}, {'4': '3'}, {'3': '5'}, {'0': '7'}, [], [], [], []]

我试过这个:

for x in a:
    for y in x.values():
        print(y)

不工作

for x in a:
    for y in x.itervalues():
        print(y)

不工作

for x in a:
    for y in x.items():
        print(y)

不工作

无论如何要这样打印? :

1 0
9 2
4 3
3 5
0 7

keys = 1,9,4,3,0
values = 0,2,3,5,7

【问题讨论】:

  • a 是字典和列表的混合列表,而不是字典列表。

标签: python string list dictionary


【解决方案1】:

一种可能的解决方案是使用列表推导过滤掉非字典,然后将字典转换为键值元组,并用zip 分隔键和值:

k,v = zip(*[list(x.items())[0] for x in a if isinstance(x, dict)])
print(k,v)
#('1', '9', '4', '3', '0') ('0', '2', '3', '5', '7')

【讨论】:

    【解决方案2】:

    如果您想要并排的键/值对输出,那么您可以执行以下操作(如果您的任何字典要包含多个键/值对,则需要更改代码):

    for x in a:
        if isinstance(x, dict):
            # "if isinstance" is here just to ignore the lists in your list,
            # you may want to do something else with those
            print(x.keys(), x.values())
    
    # (['1'], ['0'])
    # (['9'], ['2'])
    # (['4'], ['3'])
    # (['3'], ['5'])
    # (['0'], ['7'])
    

    如果您需要处理字典项中的多个键/值对并仅打印值(减去格式),则如下所示:

    for x in a:
        if isinstance(x, dict):
            tups = x.items()
            for tup in tups:
                print('{} {}'.format(tup[0], tup[1]))
    
    # 1 0
    # 9 2
    # 4 3
    # 3 5
    # 0 7
    

    【讨论】:

    • 谢谢先生。是的,这也有效。我尝试制作另一个不同的字典来包含更多要测试的键。
    • 先生有没有办法以整数形式打印它,只有 1、9、4、3、0 而不是像上面那样的另一个列表?
    • 您的意思是删除列表格式(括号和单引号)的方法吗?然后您是否尝试先打印一行中的键,然后打印一行中的值,例如来自@DYZ 的答案,或者像此答案一样在堆叠的键/值对输出中?
    • 是的。如果可能的话,我希望它只是整数。我试过这个:list(map(int,(x.keys()))) 但它输出另一个列表: [1][2] 像这样。有没有办法让它只有 1 2
    • 很高兴你得到它。在我的答案中添加了一个示例,如果字典中的键/值对不只供其他任何可能来查找的人使用,也可以处理它。
    猜你喜欢
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多