-2

I have some code like:

def example(*, current_age:int):
    my_final_return={}
    const1 = int(40)
    const2 = int(45)
    const3 = int(50)
    ages_list = (current_age, const1, const2, const3)
    new_list = ()
    for i in ages_list:
        new_list += (i,)
    for i in new_list:
        my_final_return[i] = {
            "current_age": i * 2   
        }
    return my_final_return

When I try using this code with a current_age that matches one of the constant values, I only get three keys in the result:

>>> example(current_age=40)
{40: {'current_age': 80}, 45: {'current_age': 90}, 50: {'current_age': 100}}

I read Duplicate values in a Python dictionary, so I understand that it is not possible to have duplicate keys in the dictionary. To work around this, I tried returning a tuple instead. This allowed me to duplicate "keys", but I only got (40, 40, 55, 50) as the result - the current_age information is missing.

This code will be part of a web API implementation (using FastAPI), so I need to return something that can be converted to JSON.

How can I structure the data to return all the information?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Ragnar
  • 171
  • 3
  • 13
  • 3
    Dictionaries cannot contain duplicate keys. – Andrej Kesely Jul 28 '22 at 19:51
  • 1
    as you already know that you cannot have duplicate keys in dictionary. One way you can do is to return the result as a string that looks like a dictionary. – Nesi Jul 28 '22 at 19:52
  • 1
    I am having a hard time understanding what you are trying to do. What is your expected output exactly? And with different inputs? And how is using a tuple with 4 pairs not working for you (as a comment on your other question) – JarroVGIT Jul 28 '22 at 20:10
  • 1
    You know that dictionaries can't contain duplicate keys, so one possibility is to have the all the values in the duplicate keys in a list assigned to a key with the same name. – OmegaO333 Jul 28 '22 at 20:12
  • Thanks all for your reply, JarroVGIT can a tuple works like a dictionary? What I expected is return multiple values for each number as you can see in the second picture I return a dictionary with "current_age":value but I need to display, current_age, name, address in each number or key. – Ragnar Jul 28 '22 at 20:17
  • @AlphaA999 what you say is really interesting too but the result will be always 3 keys and I need 4 even if the values al duplicated. – Ragnar Jul 28 '22 at 20:19
  • I can't understand the question. Can you show an example of what the input might be, and what the resulting output should be? Please read [ask] and [mre]. Also, [please do not upload images of textual program output when asking a question.](//meta.stackoverflow.com/q/285551) – Karl Knechtel Jul 28 '22 at 20:22
  • It seems as though the question is really "what should I return?" We can't help you with this; we can't *design* the functionality for you. Make sure you understand what is possible in JSON, and come up with a data structure that represents the information you need. – Karl Knechtel Jul 28 '22 at 20:24
  • "but the problem is that I need to return a dictionary or a json." It's not clear what this means. JSON is a **format**; "a json" doesn't make sense, in the same way that "an XML" doesn't make sense. Please try to read the documentation and give us a reference for that specification, quoting the relevant part. – Karl Knechtel Jul 28 '22 at 20:27
  • if you want to use a dictionary that can have multiple values for the same key, you can use [`werkzeug.datastructures.MultiDict`](https://werkzeug.palletsprojects.com/en/2.2.x/datastructures/#werkzeug.datastructures.MultiDict) I understand that this is not exactly what you need, but as an option – QwertYou Jul 28 '22 at 20:29
  • 1
    @KarlKnechtel can't you reproduce my code? My question is very simple as you can see in my post: I need to return a dictionary, I have a list of numbers I use as keys (code example) I loop the list and return the dictionary with this list of numbers but I need to return this dictionary with 4 values even if they are duplicates. Do I need to edit my question with this explanation? Thanks again. – Ragnar Jul 28 '22 at 20:36
  • I don't have FastAPI set up, so no. Is FastAPI required in order to understand the problem? Or is it simply about computing an appropriate result? Either way, we need to understand **what the appropriate result should be**. If it's because of a FastAPI requirement, then we only need to see **that requirement** in the documentation. If it's up to you, then it's up to you, and you need to make the decision before posting. – Karl Knechtel Jul 28 '22 at 20:41
  • "but I need to return this dictionary with 4 values even if they are duplicates. " **Why** do you (believe that you) need to return a dictionary? It is **not possible** to return a dictionary with duplicate **keys**, because **there is no such thing**. – Karl Knechtel Jul 28 '22 at 20:43
  • Did you try returning a tuple or a list, for example? **What happened** when you tried that, and **why is that a problem**? – Karl Knechtel Jul 28 '22 at 20:44
  • 2
    @KarlKnechtel yeah this is definitely not a FastAPI related question. It is about not understanding data structures and being stubborn that it really *has* to be a dictionary while OP just wants a structure with 4 items in it. A list with single item dictionaries would do the trick. – JarroVGIT Jul 28 '22 at 20:44
  • @KarlKnechtel `what the appropriate result should be` a dictionary, I cannot edit my comment where I wrote JSON (never mind about this comment) I tried to return a Tuple as you can see in my code also, and I put a picture also of the result, as I mentioned in my question I need to return not only the number the number is just a key every number has other properties like: current_age, name, address. – Ragnar Jul 28 '22 at 20:46
  • " I tried to return a Tuple as you can see in my code also, and I put a picture also of the result," Okay, so the problem is that the tuple does not contain all the necessary information? What if you tried adding that information to the elements of the tuple? For example, did you consider the idea of using *dictionaries as the elements of* the tuple? – Karl Knechtel Jul 28 '22 at 20:48
  • @KarlKnechtel "did you consider the idea of using dictionaries as the elements of the tuple?" few hours ago I didnt know Tuples exists, I will try to investigate more information following your comments and then I'll try to edit my question, I really appreciate your time. – Ragnar Jul 28 '22 at 20:51
  • 1
    Lists and tuples are more or less interchangeable here. If you are not familiar with them, it would be better to follow a Python tutorial from the beginning and learn the fundamentals before trying to work with web APIs. – Karl Knechtel Jul 28 '22 at 20:52

2 Answers2

1

As per the comments, you can't force a dictionary to always have 4 keys with 4 corresponding values, if the keys are overlapping. So, a structure as such:

{
    10 : "some text",
    10 : "other text",
    20 : "yet other text"

}

is impossible.

If you always have 4 items in your data structure, then there are multiple options to choose from. For example, you can have a list with 4 items that are single-item dictionaries like this:

item1 = {10 : "some text"}
item2 = {10 : "other text"}
item3 = {20 : "yet other text"}
item4 = {30 : "wuuuut"}

final_result = [item1, item2, item3, item4]

There are numerous possibilities, using a Tuple is another example. The key thing here is: there are always 4 items, and you can loop over the list and perform any logic you like.

Finally, if it really has to be a dictionary, then you should use a list as value per key. Something like this:

final_result = {
    10 : [{"text": "some text"}, {"text":"other text"}],
    20 : [{"text": "yet other text"}],
    30 : [{"text":"wuuut"}]
}

This way, you can 'reuse' existing keys by just adding to it. But then again, if you really want to force 4 elements, then a list would be much easier to control.

JarroVGIT
  • 4,291
  • 1
  • 17
  • 29
  • This approach does not depend on the number of items; we don't have to start with separate variables, but can instead just create the final list (or tuple) directly. – Karl Knechtel Jul 28 '22 at 20:54
1

Use a list (or tuple) of key-value pairs. By "pair" we simply mean either a list or tuple with two elements, the first of which is what would have been a "key" and the second of which would have been the "value".

(When converted to JSON, lists and tuples will both turn into what JSON calls "arrays", with square-bracket syntax. JSON parsers will usually turn these into lists when you read them back into other Python code.)

Thus, our target desired output (using a list of tuples) might be

[(40, {'current_age': 80}), (40, {'current_age': 80}), (45, {'current_age': 90}), (50, {'current_age': 100})]

And we could produce it like:

def example(*, current_age:int):
    my_final_return = []
    const1 = int(40)
    const2 = int(45)
    const3 = int(50)
    ages_list = (current_age, const1, const2, const3)
    new_list = ()
    for i in ages_list:
        new_list += (i,)
    for i in new_list:
        my_final_return.append(
            (i, {"current_age": i * 2})
        )
    return my_final_return

Or, more simply (there is no reason to make the new_list copy of ages_list; there is no reason to convert integer literals to integer; we can put the constant values directly into the ages_list; and we can use a list comprehension to process the data rather than a for loop):

def example(*, current_age:int):
    return [
        (i, {"current_age": i * 2})
        for i in (i, 40, 45, 50)
    ]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153