【问题标题】:How to convert a dictionary of strings into a block of text with python如何使用python将字符串字典转换为文本块
【发布时间】:2017-07-06 16:43:14
【问题描述】:

我有一个充满字符串值 k-v 对的字典,我希望每个用 ==>& 分隔,然后打印到换行符。

我使用数组来调解转换,这似乎不必要且不雅。 如果可能,我想在 1 行中执行此操作。

这是我所拥有的:

foo_dict = {
    'a' : '1',
    'b' : '2',
    'c' : '3',
    }
foo_list = []
for k, v in foo_dict.items():
    foo_list.append('{} ==> {}'.format(k, v))
foo_text = '\n'.join(foo_list)

这将打印:

b ==> 2
c ==> 3
a ==> 1

顺序无关紧要(否则我只会使用OrderedDict。)重要的是所有 k-v 对都以正确的格式打印。

【问题讨论】:

  • ...1 line if possible - 为什么?
  • @wwii 为了更好地阅读!

标签: python string dictionary


【解决方案1】:

下面的单行就可以了:

foo_text = '\n'.join('{} ==> {}'.format(*t) for t in foo_dict.items())

或者我们可以使用starmap(..):

from itertools import starmap

foo_text = '\n'.join(starmap('{} ==> {}'.format,foo_dict.items()))

两者都生成:

>>> '\n'.join('{} ==> {}'.format(*t) for t in foo_dict.items())
'b ==> 2\na ==> 1\nc ==> 3'
>>> '\n'.join(starmap('{} ==> {}'.format,foo_dict.items()))
'b ==> 2\na ==> 1\nc ==> 3'

str.join 只接受任何类型的iterable,因此我们可以使用生成器或列表。我们还可以通过使用列表推导来稍微提升前者:

foo_text = '\n'.join(['{} ==> {}'.format(*t) for t in foo_dict.items()])

话虽如此,请注意仅仅因为有可能而编写单行代码并不是一个好的理由。您应该始终追求可读性(鉴于它不会改变时间复杂度或对效率产生重大影响)。在这种情况下,这可能不是问题。但神秘的单行代码是 un-Pythonic。

【讨论】:

    【解决方案2】:

    如果您希望它是单行的,您可以编写一个列表推导式并将字符串元素与\n 连接起来:

    print('\n'.join(["{} ==> {}".format(k, foo_dict[k]) for k in foo_dict]))
    

    【讨论】:

      【解决方案3】:

      虽然此处的其他答案提供了格式化常规字典的好方法,但如果您有很多需要此功能的情况,您可能需要考虑通过继承 collections.UserDict 并覆盖其默认值 @ 创建自定义字典对象987654322@:

      >>> from collections import UserDict
      >>> 
      >>> class custom_dict(UserDict):
      ...     def __repr__(self):
      ...         return '\n'.join('{} ==> {}'.format(k, v) for k, v in self.data.items())
      ... 
      >>> foo_dict = {
      ...     'a' : '1',
      ...     'b' : '2',
      ...     'c' : '3',
      ...     }
      >>> 
      >>> new_dict = custom_dict(foo_dict)
      >>> new_dict
      a ==> 1
      b ==> 2
      c ==> 3
      >>>
      

      【讨论】:

        【解决方案4】:

        你可以试试这个:

        new_list = [a+"==>"+b if isinstance(a, str) and isinstance(b, str) else str(a)+"==>"+str(b) for a, b in foo_dict.items()]
        
        #then, just print the contents
        
        for i in new_list:
            print i
        

        【讨论】:

        • 这种方法的一个潜在问题是,如果键或值不是字符串,它会出错。此处并非如此,但也许您应该在答案中添加“警告”。
        • @WillemVanOnsem 或者在连接之前将a 和b 转换为字符串。
        • 我真的不明白为什么要使用三元运算符:str(x) == x if x 是一个字符串。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-05-19
        • 2013-03-13
        • 2017-03-23
        • 1970-01-01
        • 1970-01-01
        • 2020-12-29
        • 2020-11-17
        相关资源
        最近更新 更多