0

I want to add username and dateTimeHold to bigData, if it already exists, then I only want to add dateTimeHold, else add username and dateTimeHold.

When I'm trying with this code, it's just overwriting:

dateTimeHold = ('09-07-2019', '09.00 - 16.00', 'Red')
username = 'James'
bigData = {
        'Peter': [('08-07-2019', '06.00 - 07.00', 'Blue')], 
        'James': [('08-07-2019', '06.00 - 07.00', 'Blue')]
        }

if username != bigData.keys():
    listTime = []
    listTime.append(dateTimeHold)
    bigData[username] = listTime
else:
    bigData[username][listTime].append(dateTimeHold)

Output:

{
    'Peter': [('08-07-2019', '06.00 - 07.00', 'Blue')], 
    'James': [('09-07-2019', '09.00 - 16.00', 'Red')]
}

What I want it to do:

{
    'Peter': [('08-07-2019', '06.00 - 07.00', 'Blue')], 
    'James': [('08-07-2019', '06.00 - 07.00', 'Blue'), ('09-07-2019', '09.00 - 16.00', 'Red')]
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

0

Proper sintax

if username not in bigData.keys():
    bigData[username] = [dateTimeHold]
else:
    bigData[username].append(dateTimeHold)

About your if condition

Using if username != bigData.keys(): will always be true because anything your variable username is will be different of dict_keys(['Peter', 'James']).

If you want to see if a value is inside a list you should use in or not in instead

  • 'Peter' != bigData.keys() is True
  • 'Peter' not in bigData.keys() is False

About your else

The sintax is not right, listTime doesn't exists in your else scope.

Besides that check out this content of adding new keys in dict to understand why bigData[username][listTime].append(dateTimeHold) generates an error and whybigData[username].append(dateTimeHold) works.

Filipe Filardi
  • 170
  • 2
  • 12
0

Try the code and see the comments in line for the corrections

dateTimeHold = ('09-07-2019', '09.00 - 16.00', 'Red')
username = 'James'
bigData = {'Peter': [('08-07-2019', '06.00 - 07.00', 'Blue')], 
           'James': [('08-07-2019', '06.00 - 07.00', 'Blue')}
if username not in bigData.keys(): #1. Check for the username in the keys
    listTime = []
    listTime.append(dateTimeHold)
    bigData[username] = listTime
else:
    bigData[username].append(dateTimeHold) #2.right way to append