简体   繁体   中英

Convert lists inside dictionary to strings?

I have a dictionary that looks like this:

dict = {1092267: [0.187], 524292: [-0.350], 524293: [0.029], 524294: [0.216]}

So there is an ID followed by a value inside a list. I want the lists to be strings like this:

dict = {1092267: '0.187', 524292: '-0.350', 524293: '0.029', 524294: '0.216'}

How can I do this?

EDIT: all the answers given are giving me the error: 'str' object has no attribute 'items' when I use a bigger list

iteritems() and dict comprehensions to the rescue:

d = {k: str(v[0]) for k,v in d.iteritems()}

But please don't use dict as a name for your variable

Use iteritems and dict comprehension .Dont use dict as variable name

>>>{i:str(j[0]) for i,j in dict.iteritems() }
{524292: '-0.35', 524293: '0.029', 524294: '0.216', 1092267: '0.187'}

In Python3

>>>{i:str(j[0]) for i,j in dict.items() }

Try to this.

for key, value in mydict.items():
    mydict.update({key: str(value[0])})

Output:

{1092267: '0.187', 524292: '-0.35', 524293: '0.029', 524294: '0.216'}
for key, value in dict.viewitems():
    dict[key] = str(value[0])

OUTPUT:

{1092267: '0.187', 524292: '-0.35', 524293: '0.029', 524294: '0.216'}

I can't comment, but Roman Pekar's answer is the right answer. But it won't work in Python 3.x as d.items now does wat d.iteritems used to do:

d = {k: str(v[0]) for k,v in d.iteritems()}

The solution in Python 3 therefore is:

d = {k: str(v[0]) for k,v in d.items()}

You may want to check if the value you are are trying to change is actually a list, in order to prevent errors:

d = {k: str(v[0]) for k,v in d.items() if isinstance(v, (list,))}

Output:

{1092267: '0.187', 524292: '-0.35', 524293: '0.029', 524294: '0.216'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM