【问题标题】:How do I save changes made in a dictionary values to itself?如何将字典值中所做的更改保存到自身?
【发布时间】:2020-09-11 12:53:31
【问题描述】:

我有一本字典,其中的值是一个元组列表。

        dictionary = {1:[('hello, how are you'),('how is the weather'),('okay 
        then')], 2:[('is this okay'),('maybe It is')]}

我想让每个键的值成为单个字符串。所以我做了一个函数来完成这项工作,但我不知道如何将它插入到原始字典中。

我的功能:


   def list_of_tuples_to_string(dictionary):
       for tup in dictionary.values():
           k = [''.join(i) for i in tup] #joining list of tuples to make a list of strings
           l = [''.join(k)] #joining list of strings to make a string
           for j in l: 
               ki = j.lower() #converting string to lower case
       return ki

我想要的输出: dictionary = {1:'你好,那天气好吗', 2:'这样好吗'}

【问题讨论】:

  • 只需创建新字典并将所有元素放入其中。
  • for k in dictionary: dictionary[k] = " ".join(dictionary[k]).lower().strip()

标签: python list dictionary tuples


【解决方案1】:

您可以简单地覆盖字典中每个键的值:

for key, value in dictionary.items():
    dictionary[key] = ' '.join(value)

注意 join 语句中的空格,它用空格连接列表中的每个字符串。

【讨论】:

    【解决方案2】:

    它可以比你想象的更简单,只需使用理解 dicts

    >>> dictionary = {1:[('hello, how are you'),('how is the weather'),('okay then')], 
                      2:[('is this okay'),('maybe It is')]}
    >>> dictionary = {key:' '.join(val).lower() for key, val in dictionary.items()}
    >>> print(dictionary)
    {1: 'hello, how are you how is the weather okay then', 2: 'is this okay maybe It is'}
    

    现在,我们来看看方法

    1. 我们用dict.items()遍历字典中的键和值
    2. 将键赋值为自身,并将值赋值为由列表中每个元素组成的字符串。
    3. 这些元素用一个空格连接在一起并设置为小写。

    【讨论】:

    • 它;给我一个错误提示 str expected and tuple found!
    【解决方案3】:

    试试:

    for i in dictionary.keys():
        dictionary[i]=' '.join(updt_key.lower() for updt_key in dictionary[i])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-27
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多