Conversion of single string to list of strings when new strings are added

Viewed 178

I can't find an answer. I read a dictionary from file, it has a string value for a key. Then I check if a new value is already in the dictionary, if it isn't then I want to append it to the previous string and to get a list of values for a given key.

For example if I have a dictionary

dict = {"vehicles": "car", "animals": "cat"}

and the following condition is true

if "dog" not in dict["animals"]:

I'd like to get the output

dict = {"vehicles": "car", "animals": ["cat", "dog"] }
5 Answers

start with a dictionary with values as set of strings

d = {"vehicles": {"car"}, "animals": {"cat"}}

Then adding twice a new value only adds it once (and lookup is fast since it uses hashes):

d["animals"].add('dog')
d["animals"].add('dog')

>>> d
{'animals': {'dog', 'cat'}, 'vehicles': {'car'}}

If you have the dictionary as input like in your question, you can transform it easily with values as set with dictionary comprehension like this:

loaded_d = {"vehicles": "car", "animals": "cat"}  # dict just loaded from file
d = {key:{value} for key,value in loaded_d.items()}

You just need to update animals list by using append method.

dict = {"vehicles": "car", "animals": "cat"}

def appendItem(item):
  if item not in dict["animals"]:
      if not isinstance(dict["animals"], list):
          dict["animals"] = [dict["animals"]]
      dict["animals"].append(item)

appendItem("dog")
appendItem("dog")
appendItem("rabbit")
appendItem("cat")

Output

=> {'vehicles': 'car', 'animals': ['cat', 'dog', 'rabbit']}
>>> if "dog" not in dict["animals"]:
...     dict["animals"] = [dict["animals"], "dog"]

Another way is to try append the element to the list and if it fails make the dictionary value a list:

dic = {"vehicles": "car", "animals": "cat"}
if "dog" not in dic["animals"]:
    try:
        dic["animals"].append("dog")
    except:
        dic["animals"] = [dic["animals"], "dog"]

Gives output:

{'vehicles': 'car', 'animals': ['cat', 'dog']}

In this way if you have a single element the except part will be executed, making the value a list of string. If you then try to add another element it will be appended to the list.

Should be the easies way I think

dict = {"vehicles": {"car"}, "animals": {"cat"}}
if "dog" not in dict["animals"]:
    dict["animals"].add("dog")
Related