0

I have a list, that I wanted to convert to a dictionary.

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

Is there any way to do this, can I convert to dictionary like this by program:

{
    "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
}

Variables are boolean here.

So that I can easily pass this dictionary to my function

def updateFileAttributes(self, file_attributes):
    m = models.FileAttributes(**file_attributes)
    m.save()
Alvaro
  • 2,227
  • 1
  • 14
  • 11
Laxmikant Ratnaparkhi
  • 4,745
  • 5
  • 33
  • 49

3 Answers3

4

You can't get the name of a variable after you put it into a list, but you can do:

In [211]: is_text = True

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

Note that the value stored in d are boolean constants once you create it, you cannot change the value of d['is_text'] dynamically by changing variable is_text because a bool is immutable.

In your case, you don't have to make file_attributes a compound data structure, just make it a keyword argument:

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

then you can call the function this way:

yourObj.updateFileAttributes(is_text=True, ...)
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
0

I have made few assumptions here to derive this result. The variables in the List are the only available bool variables in the scope.

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

or if you have enforced an naming convention for your variables

{ x:eval(x) for x in  dir() if x.startswith('is_') }
rogue-one
  • 11,259
  • 7
  • 53
  • 75
-1

Below code works.

For Variables to String

>>> 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}

For string only.

    >>> lst = ['a','b','c']
    >>> lst
    ['a', 'b', 'c']
    >>> {item:item for item in lst}
    {'a': 'a', 'c': 'c', 'b': 'b'}
Pavan Gupta
  • 17,663
  • 4
  • 22
  • 29