1

Please check the below code and my output. I have run my code i got the below output but i want Expected Result.

list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']

Expected Result is :-

{
  "ABCD": "SATARA",
  "XYZ": ["MUMBAI", "PUNE"]
  "PQR": "43566",
  "LMN": "455667"
}

My Code :-

list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']

    for each_split_data in list_data:
        split_by_colon = each_split_data.split(":")
        if split_by_colon[0] is not '':
            if split_by_colon[0] in splittded_data_dict:
                # append the new number to the existing array at this slot
                splittded_data_dict[split_by_colon[0]].append(split_by_colon[1])
            else:
                # create a new array in this slot
                splittded_data_dict[split_by_colon[0]] = [split_by_colon[1]]

    print(json.dumps(splittded_data_dict, indent=2), "\n")

My OUTPUT :-

{
  "ABCD": [
    "SATARA"
  ],
    "REF": [
    "MUMBAI.",
    "PUNE"
  ],
  "PQR": [
    "43566"
  ],
  "LMN": [
    "455667"
  ]
}

How can i solve the above problem?

0

4 Answers 4

1

The best thing to do in my opinion would be to use a defaultdict from the collections module. Have a look:

from collections import defaultdict


list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']

res = defaultdict(list)
for item in list_data:
    key, value = item.split(':')
    res[key].append(value)

which results in:

print(res)
# defaultdict(<class 'list'>, {'ABCD': ['SATARA'], 'XYZ': ['MUMBAI', 'PUNE'], 'PQR': ['43566'], 'LMN': ['455667']})

or cast it to dict for a more familiar output:

res = dict(res)
print(res)
# {'ABCD': ['SATARA'], 'XYZ': ['MUMBAI', 'PUNE'], 'PQR': ['43566'], 'LMN': ['455667']}
Sign up to request clarification or add additional context in comments.

Comments

1

From what I understand by the description of your problem statement, you want splittded_data_dict to be a dictionary where each value is a list For this purpose try using defaultdict(). Please see the example below.

from collections import defaultdict

splittded_data_dict = defaultdict(list)
splittded_data_dict['existing key'].append('New value')

print(splittded_data_dict)

Comments

0

You can use the isinstance function to check if a key has been transformed into a list:

d = {}
for i in list_data:
    k, v = i.split(':', 1)
    if k in d:
        if not isinstance(d[k], list):
            d[k] = [d[k]]
        d[k].append(v)
    else:
        d[k] = v

d becomes:

{'ABCD': 'SATARA', 'XYZ': ['MUMBAI', 'PUNE'], 'PQR': '43566', 'LMN': '455667'}

Comments

0

Let's append all possible key values from the string items in the list_data. Get the list of unique items. Now loop through the list_data and check if the first item of the ":" split string matched with the list a and if matches append to a temporary list and at last assign that temporary list as the value to the key of the item in the list a.

Here is oneliner using dict comprehension and list comprehension simultaneously :

   c = {i : [j.split(":")[1] for j in list_data if j.split(":")[0] == i ][0] if len([j.split(":")[1] for j in list_data if j.split(":")[0] == i ])==1 else [j.split(":")[1] for j in list_data if j.split(":")[0] == i ] for i in list(set([i.split(":")[0] for i in list_data]))}

Output should be :

# c = {'LMN': '455667', 'ABCD': 'SATARA', 'PQR': '43566', 'XYZ': ['MUMBAI', 'PUNE']}

Here is the long and detailed version of the code :

list_data = ['ABCD:SATARA', 'XYZ:MUMBAI', 'PQR:43566', 'LMN:455667', 'XYZ:PUNE']
a = []
for i in list_data:
    a.append(i.split(":")[0])
a = list(set(a))
b = {}
for i in a:
    temp = []
    for j in list_data:
        if j.split(":")[0] == i:
            temp.append(j.split(":")[1])
    if len(temp) > 1:
        b[i] = temp
    else:
        b[i] = temp[0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.