Home > Back-end >  Dictionary values are in "set", how can I manage to remove the sets?
Dictionary values are in "set", how can I manage to remove the sets?

Time:08-22

dict = {'a': {'Islamabad'}, 'b' : {'Islamabad'}, 'c': {'Paris'},
       'd': {'Bern'}, 'e': {'Moscow'}}

result wanted:

dict = {'a': 'Islamabad', 'b' : 'Islamabad', 'c': 'Paris',
       'd': 'Bern', 'e': 'Moscow'}

CodePudding user response:

A simple way to get one element from a set is set.pop().

dct = {'a': {'Islamabad'}, 'b' : {'Islamabad'}, 'c': {'Paris'},
       'd': {'Bern'}, 'e': {'Moscow'}}

dct = {k: v.pop() for k, v in dct.items()}
print(dct)

v.pop() modifies the original set v. If this is not desired, use next(iter(v)).

P.S. don't use dict as a variable name

CodePudding user response:

You can convert set to string using * with str() function ( str(*set) ). This way it will remove brackets from the string

You have to loop over the dict and change each value to string like this

dict1 = {'a': {'Islamabad'}, 'b' : {'Islamabad'}, 'c': {'Paris'}, 'd': {'Bern'}, 'e': {'Moscow'}}

dict1 = {k: str(*v) for k, v in dict1.items()}

output: {'a': 'Islamabad', 'b': 'Islamabad', 'c': 'Paris', 'd': 'Bern', 'e': 'Moscow'}

and also, don't use "dict" to name your dictionaries. "dict" is python built-in word which may lead to error in some scenarios

CodePudding user response:

Extremely poor code, please don't use this in any other cases than your own, but this works with your current example.

import ast

dictt = {'a': {'Islamabad'}, 'b' : {'Islamabad'}, 'c': {'Paris'},
       'd': {'Bern'}, 'e': {'Moscow'}}

dictt = str(dictt).replace("{","") #Convert to string and remove {
dictt = "{"   dictt.replace("}","")  "}" #remove } and re-add outer { }
dictt = ast.literal_eval(dictt) #Back to dict

print(dictt) 

output: {'a': 'Islamabad', 'b': 'Islamabad', 'c': 'Paris', 'd': 'Bern', 'e': 'Moscow'}

  • Related