0

Say I have a list like this:

alist = [{'key': 'value'}]

And then I convert it to a dictionary like this

adict = dict(alist)

The formatting becomes

{'{''key: 'value}'}

This makes it so I can't access the data from the dictionary. Is there a way to convert the list to a dictionary without there being extra {' '} -- brackets and single quotes

martineau
  • 112,593
  • 23
  • 157
  • 280
the_martian
  • 622
  • 8
  • 21

3 Answers3

1

You can use the index 0 to avoid the extra { } braces because the dictionary can be accessed as alist[0]. Moreover, you do not need dict additionally because your list content is already a dictionary

adict = alist[0]

Now you get the desired behavior

print (adict)
# {'key': 'value'}
Sheldore
  • 35,129
  • 6
  • 43
  • 58
  • @DeveshKumarSingh: It works for me. Anyway, `dict` is not need here because the list contains already a dictionary. Check my edit – Sheldore Mar 23 '19 at 23:41
1

If you first structure your list by swapping the curly braces, you won't have any issues using this :)

dict([('A', 1), ('B', 2), ('C', 3)])

David S
  • 1,406
  • 1
  • 13
  • 21
0

If your objective is to initialise a dictionary object with a key value pair (or a bunch of key value pairs), why would you use a list first?

You could simple write

adict = {'key': 'value', 'Hello': 'world' }

print(adict)

Gro
  • 1,472
  • 1
  • 10
  • 18