0

This is the situation, I will write the example code:

user = 'Boby'
a = ['hana', 'dul', 'se']
b = method.prepareSentence(a, user)

first_sentence = method.prepareSpeech('short_speech', user, b)
second_sentence = method.prepareDebates('quick_debates', user, b) 

but here I want a to have one more element in the list, so

a = ['hana', 'dul', 'se', 'sou']

Is it possible to do this without duplicating variables and making two versions of a?

I found this solution but this is very primitive and will make the script bigger and I want to make changes to many other similar scripts:

a1 = ['hana', 'dul', 'se']
b1 = method.prepareSentence(a, user)
a2 = ['hana', 'dul', 'se', 'sou']
b2 = method.prepareSentence(a, user)

first_sentence = method.prepareSpeech('short_speech', user, b1) second_sentence = method.prepareDebates('quick_debates', user, b2)

BumberAZ
  • 13
  • 4
  • 1
    That's not a dictionary; it's a set. You can do `a2 = a1 | {"sou"}` with sets. – Selcuk Nov 15 '21 at 07:10
  • You are right @Selcuk I am still mixing up the terms, I am a beginner. What you suggest is of course better and shorter way but, doesn't it still mean that I have to use two different variables? – BumberAZ Nov 15 '21 at 07:16
  • Are you looking for `a.append('sou')`? Lists (which you're using now) also support the `+` operator, if you want to create a new list with the extra element (`a + ['sou']`). – Blckknght Nov 15 '21 at 07:41
  • This sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Maybe you should first explain why you think you need to do this in the first place. Are there too many variables that need to be created? If yes, it smells bad design. – Selcuk Nov 15 '21 at 13:03

1 Answers1

0

The question asks for a solution with a dictionary, however the shown code is given with sets. Nevertheless there is a solution for both types.

Via PEP584 it is recommends to use the | operator for sets and dictionaries to merge two dictionaries.

a = {"a":'hana', "b": 'dul', "c":'se'}
a2 = {"d": "sou"} | a

More information on merging dictionaries can be found in this question.

thomas
  • 381
  • 2
  • 7
  • I am embarrassed for calling it a dictionary instead of a set. That operator is very helpful but I was thinking if there is another way to do it without creating new variables, but I guess that's impossible – BumberAZ Nov 15 '21 at 07:22
  • @BumberAZ you can use a list or an actual dictionary and add the new values there, that way you can access them by their keys or indexes and it wouldn't take up the namespace – Matiiss Nov 15 '21 at 07:23