Define a function to generate a dictionary

Viewed 184
def create_dictionary(params)

How do I generate a dictionary from a string value which comes from its parameter named params. The dictionary is created with the use of zip function to handle the keys and values which are generated from params

How do I make the output of this:

print(create_dictionary('name:= Jack ; grade:=3'))

To be like this:

{'name': 'Jack', 'grade': '3'}
4 Answers
def create_dictionary(string1):
  s = string1.split(';')
  dic = {}
  for i in s:
     key, value = i.split(':=')
     dic[key] = value
  return dic

If the string's syntax is same all the time, you can split the string accordingly. In this case:

First split them with ; to separate dictionary values.

Then split rest with := to get the key and the value. You may want to trim the resulting key and value to remove the white spaces around.

Note: If data itself contains the ; or :=, this solution will fail.

Edit

In addition to the Daniel Paul's answer for removing the white spaces:

def create_dictionary(string1):
  s = string1.split(';')
  dic = {}
  for i in s:
     key, value = i.split(':=')
     dic[key.strip()] = value.strip()
  return dic

Before: {'name': ' Jack ', ' grade': '3'} after {'name': 'Jack', 'grade': '3'}

One-liner using python's dict comprehension:

def create_dictionary(string):
    {a.strip():b.strip() for a,b in [i.split(':=') for i in string.split(';')]}

You can use the split method and split := or you can follow up my code

def dict_fun(*args):
    dict = {}
    cnt = 0
    count = 0
    while cnt < len(args):
        for i in args[cnt]:
            if i == ':':
                print(count)
                dict[args[cnt][0:count]] = args[cnt].strip().replace(' ','')[count+2:]
                break
            else:
                count += 1
        cnt += 1
        count = 0
    return(dict)
print(dict_fun('name:=Jack', 'grade:=3'))

OUTPUT

{'name': 'Jack', 'grade': '3'}

Now you can give as many argument as many you want inside dict_fun('name:=jack','grade:=3',etc..) so as of taking single string now you can give mutiple string argument to the function and it would return you the dict of that string..

Related