Home > Back-end >  After merging dicts in a list how can I convert it back to type dict not string?
After merging dicts in a list how can I convert it back to type dict not string?

Time:09-02

hi there i have a list of dicts

dict = [{A: 2}, {B: 2},]

i am trying to merge them together like this

dict = [{A: 2, B: 2}]

i try doing it using this code

new_dict = ', '.join([str(x) for x in dict])

the problem i have now is my list of object is now a string . so when i run this code below

    for k, v in sorted(new_dict.items(), key=lambda item: item[1], reverse=True):
        rtn_value[k] = v
        count = count - 1
        if count == 0: return rtn_value

I get this ERROR

AttributeError: 'str' object has no attribute 'items'

after merging objects in a list how can I convert it back to type dict not string?

when i do type(new_dict) ...i can see it is a type string

new_dict <class 'str'>

CodePudding user response:

Try this:

result = {}
for item in dict:
    result.update(item)
result = [result]

Note however that

  1. you better not use reserved word dict as your variable
  2. you probably want dictionary keys to be strings ("A", not A)
  3. you haven't told us what should be the result when you have the same key in multiple dictionaries
  4. most likely you don't need the last step of wrapping the result in a list

CodePudding user response:

" This seems like an XY problem. You're asking us about how to deal with your string and convert it back to a dictionary, but the real question seems to be how to merge dictionaries, which probably shouldn't involve strings concatenation in the first place." – Blckknght

I agree with what he said in his comment. But for some reason you must convert a string back to dictionary, you can use the ast library.

from ast import literal_eval
dict_ = [{'A': 2}, {'B': 2},]

new_dict = ','.join([str(x) for x in dict_])
new_dict = list(literal_eval(new_dict))
  • Related