是否可以将变量转换为字符串?

2024-04-23 20:49:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,我想把它转换成字典。你知道吗

  L =   [ 
       is_text, 
       is_archive, 
       is_hidden, 
       is_system_file, 
       is_xhtml, 
       is_audio, 
       is_video,
       is_unrecognised
     ]

有没有办法,我可以通过程序转换成这样的字典:

{
    "is_text": is_text, 
    "is_archive": is_archive, 
    "is_hidden" :  is_hidden
    "is_system_file": is_system_file
    "is_xhtml": is_xhtml, 
    "is_audio": is_audio, 
    "is_video": is_video,
    "is_unrecognised": is_unrecognised
}

变量在这里是布尔型的。你知道吗

这样我就可以很容易地把这本字典传给我的职能部门

def updateFileAttributes(self, file_attributes):
    m = models.FileAttributes(**file_attributes)
    m.save()

Tags: text列表字典isvideosystemaudioattributes
3条回答

将变量放入列表后无法获取其名称,但可以执行以下操作:

In [211]: is_text = True

In [212]: d = dict(is_text=is_text)
Out[212]: {'is_text': True}

请注意,d中存储的值是布尔常量一旦创建它,就不能通过更改变量is_text来动态更改d['is_text']的值,因为bool是不可变的。你知道吗

在您的例子中,您不必使file_attributes成为一个复合数据结构,只需使它成为一个关键字参数即可:

def updateFileAttributes(self, **file_attributes):
    m = models.FileAttributes(**file_attributes)
    m.save()

然后可以这样调用函数:

yourObj.updateFileAttributes(is_text=True, ...)

我在这里做了一些假设来得出这个结果。 列表中的变量是作用域中唯一可用的bool变量。你知道吗

{ x:eval(x) for x in dir() if type(eval(x)) is bool }

或者如果你已经为你的变量强制了一个命名约定

{ x:eval(x) for x in  dir() if x.startswith('is_') }

下面的代码工作。你知道吗

对于要字符串的变量

>>> a = 10
>>> b =20
>>> c = 30
>>> lst = [a,b,c]
>>> lst
[10, 20, 30]
>>> {str(item):item for item in lst}
{'10': 10, '30': 30, '20': 20}

仅用于字符串。你知道吗

    >>> lst = ['a','b','c']
    >>> lst
    ['a', 'b', 'c']
    >>> {item:item for item in lst}
    {'a': 'a', 'c': 'c', 'b': 'b'}

相关问题 更多 >