Pyd
Pyd

Reputation: 6159

creating a dictionary with two lists when a key should have two values in python

hi I have two lists,

list1
['PO', 'NA', 'PO']

list2
['Post Office', 'Not Available', 'Post area']

Iam trying to get a dictionary using this two lists I tried, my_dict=dict(zip(list1,list2)) it gives,

 {'NA': 'Not Available', 'PO': 'Post area'}

but my expected output is,

 {'NA': 'Not Available', 'PO': ['Post area','Post Office']}

pls help

Upvotes: 0

Views: 203

Answers (5)

GauravInno
GauravInno

Reputation: 327

I think it can be usefull for you also.

list1 = ['PO', 'NA', 'PO', 'TCS', 'TCS']
list2 = ['Post Office', 'Not Available', 'Post area', 'Track Complaint Status', 'Tata Consultancy Service', 'Tata Consultancy Service']

output_dict = {}

for index, value in enumerate(list1):
     if not value in output_dict:
          output_dict.update({value:list2[index]})
     else:
          temp_list = [list2[index]]
          temp_list.append(output_dict[value])
          output_dict.update({value:temp_list})
 print(output_dict)

output :- {'NA': 'Not Available', 'PO': ['Post area', 'Post Office'], 'TCS': ['Tata Consultancy Service', 'Tata Consultancy Service']}

In this program no matter duplicate values in list2 and length too. You can modify this code according your exact problem.

Upvotes: 0

user8734784
user8734784

Reputation: 84

You can define your own custom dict class using dict

class ListDict(dict):
    def __init__(self, d={}):
        if isinstance(d, zip):
            for i, v in enumerate(d):
                self.__setattr__(v[0], v[1])
        else:
            self.update(d)

    def __setattr__(self, key, val):
        if key in self:
            if not isinstance(self[key], list):
                self[key] = [self[key]]
            self[key].append(val)
        else:
            self[key] = val


list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']
my_dict = ListDict(zip(list1, list2))
print(my_dict)

output:

{'PO': ['Post Office', 'Post area'], 'NA': 'Not Available'}

Upvotes: 3

Asa Stallard
Asa Stallard

Reputation: 341

This may not be exactly what you want because it gives you lists for single abbreviations, but it gives an output very similar to what you're looking for. I hope it helps.

list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']

my_dict = {}

for abbrev,value in zip(list1,list2):
    if abbrev in my_dict.keys():
        my_dict[abbrev] += [value]
    else:
        my_dict[abbrev] = [value]

edit: For the sake of completeness, the code below will NOT create lists for single items and will function ok with large lists of items with many multiple matches.

list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']

my_dict = {}

for abbrev,value in zip(list1,list2):
    if abbrev in my_dict.keys():
        if isinstance(my_dict[abbrev],str):
            my_dict[abbrev] = [my_dict[abbrev]]
        my_dict[abbrev] += [value]
    else:
        my_dict[abbrev] = value

print(my_dict)

Upvotes: 1

Aaditya Ura
Aaditya Ura

Reputation: 12669

There are two method :

First method using defaultdict:

from collections import defaultdict

list1=['PO', 'NA', 'PO']

list2=['Post Office', 'Not Available', 'Post area']

final_dict = defaultdict(list)

[final_dict[item[0]].append(item[1]) for item in zip(list1,list2)]
print(final_dict)

output:

defaultdict(<class 'list'>, {'PO': ['Post Office', 'Post area'], 'NA': ['Not Available']})

Second method :

Let's solve your issue in two step:

First zip the both list:

list1=['PO', 'NA', 'PO']

list2=['Post Office', 'Not Available', 'Post area']

zip_list=[item for item in zip(list1,list2)]

Now check if zip tuple first element is in dict or not if it is then use this awesome pattern :

final_dict={}
    for item in zip_list:
        if item[0] not in final_dict:
            final_dict[item[0]]=[item[1]]
        else:
            final_dict[item[0]].append(item[1])

Full code:

list1=['PO', 'NA', 'PO']

list2=['Post Office', 'Not Available', 'Post area']

zip_list=[item for item in zip(list1,list2)]
final_dict={}
for item in zip_list:
    if item[0] not in final_dict:
        final_dict[item[0]]=[item[1]]
    else:
        final_dict[item[0]].append(item[1])

print(final_dict)

output:

{'NA': ['Not Available'], 'PO': ['Post Office', 'Post area']}

Upvotes: 1

Kobe Nein
Kobe Nein

Reputation: 239

list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']

my_dict = dict()
for key,value in zip(list1,list2):
    if key not in my_dict:
        my_dict[key] = value
    else:
        my_dict[key] = [my_dict[key]]
        my_dict[key].append(value)

print(my_dict)

Upvotes: 1

Related Questions