4

I am trying to create a Dictionary with the following data:

ListA = ['Name', 'Age', 'Gender']
ListB = ['Alex', '22', 'Male']
        ['Kelly','21', 'Female']

ListB comes from FileB and looks like this:

Alex 22 Male,Kelly 21 Female (values tab separated, group comma separated)

Expected output:

{'Name' : 'Alex', 'Age' : '22', 'Gender' : 'Male',
 'Name' : 'Kelly', 'Age': '21', 'Gender' : 'Female'
}

I tried the following code:

fileB = glob.glob(filename + '.txt')
dfun = {}
ListB = []
for f in fileB:
    Lines = open(f, 'r').read().split(',')
    for i in Lines:
        Lines2 = i.split('\t')
        ListB.append(Lines2)
print(ListB)   # this gives me ListB in the format above. 

for i in ListB:
    List1 = ['Name', 'Age', 'Gender']
    List2 = i
    zip1 = zip(List1,i)
    zip2 = dict(zip1)
    dfun.update(zip2)
    print(dfun)

This code is only giving output as:

{'Name' : 'Kelly', 'Age': '21', 'Gender' : 'Female'}

1 Answer 1

5

Your desired output is an invalid dictionary, as dictionaries cannot contain duplicate keys, however, you can use a list comprehension and store your dictionary values as elements in a list:

ListA = ['Name', 'Age', 'Gender']
ListB = [['Alex', '22', 'Male'], ['Kelly','21', 'Female']]
result = [dict(zip(ListA, i)) for i in ListB]

Output:

[{'Name': 'Alex', 'Age': '22', 'Gender': 'Male'}, {'Name': 'Kelly', 'Age': '21', 'Gender': 'Female'}]

Edit:

result = {a:[k[i] for k in ListB] for i, a in enumerate(ListA)}

Output:

{'Name': ['Alex', 'Kelly'], 'Age': ['22', '21'], 'Gender': ['Male', 'Female']}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you Ajax, you are correct. This output is list so dictionary functions will not work here. so i cant do something like result['Name'] to get both the names. Is there a way to make a dictionary using just list B?
@HashCode Please see my recent edit, as I added a solution that forms a single dictionary result. Now you will be able to lookup desired header values and obtain results from all the lists in ListB.
perfect!! Thanks Ajax, this is helpful

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.