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
  • 119,623
  • 25
  • 170
  • 301
the_martian
  • 632
  • 1
  • 9
  • 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
  • 37,862
  • 7
  • 57
  • 71
  • @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 Silveiro
  • 1,515
  • 1
  • 15
  • 23
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,613
  • 1
  • 13
  • 19