Python 如何将在字典值中所做的更改保存到其自身?
我有一个字典,其中的值是元组列表Python 如何将在字典值中所做的更改保存到其自身?,python,list,dictionary,tuples,Python,List,Dictionary,Tuples,我有一个字典,其中的值是元组列表 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(diction
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 key, value in dictionary.items():
dictionary[key] = ' '.join(value)
请注意join语句中的空格,它用空格连接列表中的每个字符串。您可以简单地覆盖字典中每个键的值:
for key, value in dictionary.items():
dictionary[key] = ' '.join(value)
注意join语句中的空格,它用空格连接列表中的每个字符串。只需使用理解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'}
现在,让我们来看看这个方法
dict.items()
它可以做得比你想象的还要简单,只需使用理解口述
>>> 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'}
现在,让我们来看看这个方法
dict.items()
只需创建新字典并将所有元素放入其中。
对于字典中的k:dictionary[k]=“”。join(dictionary[k]).lower().strip()
只需创建新字典并将所有元素放入其中。对于字典中的k:dictionary[k]=“”。join(dictionary[k]).lower strip()
It;s给我一个错误,说str是预期的,tuple是找到的!信息技术s给我一个错误,说str是预期的,tuple是找到的!