Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6984303
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T18:31:55+00:00 2026-05-27T18:31:55+00:00

For instance, if dict[‘sample’]: //append values to dict[‘sample’] else: // assign new key to

  • 0

For instance,

if dict['sample']:
    //append values to dict['sample']
else:
    // assign new key to the python dictionary

If dict[‘sample’] is empty, Python will throw errors. Does anyone know a better way to check on this?

All I want is something like that, I will have list of data, let’s say a,a,b,c,g,g,g,g,g.

So, I want python dictionary to append the values of two a,a to dict[‘a’], and g,g,g,g,g to dict[‘g’] and so the rest as dict[‘b’] etc. A for loop will be executed to loop through the data of a,a,b,c,g,g,g,g,g.

I hope I’ve made my question clear. Any idea? Preferably, if Python’s dictionary has a way to check existing key.

EDIT

Credit goes to @Paul McGuire. I’ve figured out the exact solution I wanted based on @Paul McGuire’s answer. As shown below:

from collections import defaultdict

class Test:
   def __init__(self, a,b):
       self.a=a
       self.b=b

data = []
data.append(Test(a=4,b=6))
data.append(Test(a=1,b=2))
data.append(Test(a=1,b=3))
data.append(Test(a=2,b=2))
data.append(Test(a=3,b=2))
data.append(Test(a=4,b=5))
data.append(Test(a=4,b=2))
data.append(Test(a=1,b=2))
data.append(Test(a=5,b=9))
data.append(Test(a=4,b=7))

dd = defaultdict(list)
for c in data:
    dd[c.a].append(c.b)
print dd
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T18:31:56+00:00Added an answer on May 27, 2026 at 6:31 pm

    The old approaches of “if key in dict” or “dict.get” or “dict.setdefault” should all be set aside in favor of the now standard defaultdict:

    data = "aabcggggg"
    
    from collections import defaultdict
    dd = defaultdict(list)
    for c in data:
        dd[c].append(c)
    print dd
    

    defaultdict takes care of the checking for key existence for you, all your code has to do is 1) define a factory function or class for the defaultdict to use to initialize a new key entry (in this case, defaultdict(list)), and 2) define what to do with each key (dd[c].append(c)). Clean, simple, no clutter.

    In your particular example, you could actually use itertools.groupby, since the groups of letters are all contiguous for each grouping value. groupby returns an iterator of tuples, each tuple containing the current key value and an iterator of the matching values. The following code works by converting each tuple’s list-of-values-iterator to an actual list (in list(v)), and passing the sequence of key-valuelist tuples to the dict constructor.

    from itertools import groupby
    print dict((k,list(v)) for k,v in groupby(data))
    

    prints:

    {'a': ['a', 'a'], 'c': ['c'], 'b': ['b'], 'g': ['g', 'g', 'g', 'g', 'g']}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

New to python... I have the following class Key, that extends dict: class Key(
I have System.Collections.Generic.Dictionary<A, B> dict where A and B are classes, and an instance
For instance if you add the same string to a dict and a list?
class SortedDict(dict): def __new__(cls, *args, **kwargs): instance = super(SortedDict, cls).__new__(cls, *args, **kwargs) instance.keyOrder =
I have a simple Django-Piston Handler that creates a new instance of a model
Pointing the class method at the instance method is clearly causing problems: class A(dict):
I need to determine if a given Python variable is an instance of native
I use libcloud to create a new node instance Amazon EC2. conn.create_node returns me
I have an instance of dict with int s, float s, string s as
I have a dictionary that's created and initialized in following ways NSDictionary *dict =

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.