Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python: collections.Defaultdict() with tuples or lists as values #25

Open
sophryu99 opened this issue Sep 26, 2021 · 2 comments
Open

Python: collections.Defaultdict() with tuples or lists as values #25

sophryu99 opened this issue Sep 26, 2021 · 2 comments

Comments

@sophryu99
Copy link
Owner

Declaring a defaultdict with default values as tuples or lists

d = collections.defaultdict(lambda: (0, 0))

Add values as a tuple to keys

  • If key exists, increment the first element of the tuple by 1
  • If not, add key, value to the dictionary
for i in range(len(s) -1 , -1, -1):
            if s[i] in d.keys():
                d[s[i]] = (d[s[i]][0] + 1, i)
            else:
                d[s[i]] = (1, i)
>>> s = "loveleetcode"
>>> defaultdict(<function Solution.firstUniqChar.<locals>.<lambda> at 0x7fbb1474c940>, {'e': (4, 3), 'd': (1, 10), 'o': (2, 1), 'c': (1, 8), 't': (1, 7), 'l': (2, 0), 'v': (1, 2)})
@sophryu99 sophryu99 changed the title Python: Defaultdict with tuples or lists as values Python: collections.Defaultdict() with tuples or lists as values Sep 26, 2021
@sophryu99
Copy link
Owner Author

With set as default value

cnt = {}
        
        for log in logs:
            cnt.setdefault(log[0], set()).add(log[1])

Input:

[[0,5],[1,2],[0,2],[0,5],[1,3]]

Output:

{0: {2, 5}, 1: {2, 3}}

@sophryu99
Copy link
Owner Author

With list as default value and add list values

d = collections.defaultdict(lambda: list())
        
        for i, word in enumerate(s):
            d[word].append(i)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant