Ram Houssein
Ram Houssein

Reputation: 1

Struggling with a challenge

I was given two lists :

list1 = ["A","B","C","D","E","F",1,"G",3,"H","I","J","K","L"]
list2 = [20 ,27 ,"Arm","Leg",13 ,24 ,"Head",75 ,64 ,71 ,"Ankle", 82 ,45 ,23 ]

Using the shortest code possible, I need to create a dictionary (dictChallenge) containing only the letter from list1 and only the numbers from list2.

The output of print(dictChallenge) is:

{'A': 20, 'B': 27, 'E': 13, 'F': 24, 'G': 75, 'H': 71, 'J': 82, 'K': 45, 'L': 23 }

Upvotes: 0

Views: 68

Answers (3)

Snawar
Snawar

Reputation: 59

list1 = ["A","B","C","D","E","F",1,"G",3,"H","I","J","K","L"]
list2 = [20 ,27 ,"Arm","Leg",13 ,24 ,"Head",75 ,64 ,71 ,"Ankle", 82 ,45 ,23 ]
keys = [L for L in list1 if type(L)==str]
values = [d for d in list2 if type(d) ==int]
DictChallenge = dict(zip(keys,values))
print(DictChallenge)

Upvotes: 0

Mark
Mark

Reputation: 92440

You can zip the two lists together and then filter that list based on your conditions. You can then use that list in a dict comprehension or pass it to dict():

list1 = ["A","B","C","D","E","F",1,"G",3,"H","I","J","K","L"]
list2 = [20 ,27 ,"Arm","Leg",13 ,24 ,"Head",75 ,64 ,71 ,"Ankle", 82 ,45 ,23 ]

{k: v for k, v in zip(list1, list2) if isinstance(k, str) and isinstance(v, int)}

Which gives you:

{'A': 20,
 'B': 27,
 'E': 13,
 'F': 24,
 'G': 75,
 'H': 71,
 'J': 82,
 'K': 45,
 'L': 23}

Upvotes: 1

user15801675
user15801675

Reputation:

You could use zip and isinstance to check if it is and integer or a string.

dict1={}
for i,j in zip(list1,list2):
    if isinstance(j,int) and isinstance(i,str):
        dict1[i]=j
print(dict1)

Upvotes: 0

Related Questions