0

I have a dictionary and I want to add more values to a key.

 dict_1={"one":1,"two":2,"three and four":3}

so I want to append the key three and four from 3 to 3,4 what I have done is-

dict_1["three and four"].append(4)

but this doesn't work. Any help?

1
  • Do you mean you want to append to the value of the dict? Because that's what your code looks like you're trying to do. You really shouldn't try to change the keys. That causes havoc. Commented Nov 20, 2015 at 22:11

3 Answers 3

3

You can't append to a number. If I understand what you're trying to do correctly, you need to do this:

dict_l = { "one" : [1], "two" : [2], "three and four": [3] }
dict_l["three and four"].append(4)

Now, your values are lists, so you can append.

After running, your dict_l will look like this:

{'three and four': [3, 4], 'two': [2], 'one': [1]}
Sign up to request clarification or add additional context in comments.

5 Comments

Or maybe something like this: dict_l = { "one" : 1, "two" : 2, "three and four": [3, 4] }
I suppose you could do that, but I find things are usually easier to work with if your values are of a consistent type.
Thanks @IanMcLaird Actually I have made a GUI and I want to serializes the values of the dictionary to the entry widgets of my GUI. So, now my GUI has a "add button" that adds more rows and I want that as I enter the value to the widget my key of dictionary should append and store the value. Upon de-serializing, it should insert the values back in
This actually is doing nothing. It appends the value and then both value store in the same entry widget ['2','3'] that doesn't help.
I don't really follow you. Perhaps you should ask another question, and clearly explain what you're trying to do, and what you're seeing instead.
0

You'd be changing the type of value stored - right now it's just an int. So you'd have to get whatever's in there now, and if it's not a list, start a new one, then append the 4:

dict_1['three and four'] = [].append(dict_1['three and four'])
dict_1['three and four'].append(4)

3 Comments

[].append(dict_1['three and four']) => returns None
Yes, you mean dict_l['three and four'] = [dict_l['three and four']]
@IanMcLaird although that'd give you a list in a list if it's already a list :\
-1

You can't append a value to a dict key, but you can replace the value:

dict_1["three and four"] = 4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.