Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the list of sets like so. I basically want to convert this to the dictionary and to address duplicate keys, I want to take a text value which is longer in length:

[('hong kong', 'state'),

 ('hong kong', 'city'),

 ('hong', 'country'),

 ('kong', 'city'),

 ('hong kong', 'country')]

I wanted the below-desired result:

{'state': 'hong kong',

 'city': 'hong kong',

 'country': 'hong kong'}

I have the function that does this but I am sure that there will be an efficient & pythonic way to do this. So I have tried this:

def create_dict(l):

    d=defaultdict(list)

    for s in l:

        key = s[1]

        val = s[0]

        if d[key]:

            if len(val) > len(d[key]):

                d[key] = val

        else:

            d[key] = val

        

    return d

1 Answer

0 votes
by (36.8k points)

You can have a look at it, here is how you can use the sorted method with custom key:

lst = [('hong kong', 'state'),

       ('hong kong', 'city'),

       ('hong', 'country'),

       ('kong', 'city'),

       ('hong kong', 'country')]

def create_dict(l):

    sorted_lst = sorted(l, key=lambda x: len(x[0]))

    return {k: v for v, k in sorted_lst}

print(create_dict(lst))

Output:

{'country': 'hong kong', 'city': 'hong kong', 'state': 'hong kong'}

 If you are a beginner and want to know more about Python the do check out the python for data science

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...