Home > OS >  Create New Dictionary by taking Elements present in list and keep appending element inside the dicti
Create New Dictionary by taking Elements present in list and keep appending element inside the dicti

Time:11-30

I have list : b = ["apple", "banana", "cherry"]

I need to add all elements present in list and create new dictionary by appending it in existing dictionary.

My code:

b = ["apple", "banana", "cherry"]
c = []
def abc(key):
  a = {"aggs": { f"{key}" : { "filter": { "term": { "tag.name": f"{key}" } }, "aggs": { f"{key}_val": { "stats": { "field": "tag.value" } } } } } }
  c.append(a)

for item in b:
  abc(item)
c

My output:

[{'aggs': {'apple': {'filter': {'term': {'tag.name': 'apple'}},
    'aggs': {'apple_val': {'stats': {'field': 'tag.value'}}}}}},
 {'aggs': {'banana': {'filter': {'term': {'tag.name': 'banana'}},
    'aggs': {'banana_val': {'stats': {'field': 'tag.value'}}}}}},
 {'aggs': {'cherry': {'filter': {'term': {'tag.name': 'cherry'}},
    'aggs': {'cherry_val': {'stats': {'field': 'tag.value'}}}}}}]

Expected Output:

{"aggs":    {
                "apple" : {
                                "filter": { "term": { "tag.name": "apple" } },
                                "aggs": {
                                  "apple_val": { "stats": { "field": "tag.value" } }
                                }
                              },
                 
                "banana" : {
                                "filter": { "term": { "tag.name": "banana" } },
                                "aggs": {
                                  "banana_val": { "stats": { "field": "tag.value" } }
                                }
                              },
                   "cherry" : {
                                "filter": { "term": { "tag.name": "cherry" } },
                                "aggs": {
                                  "cherry_val": { "stats": { "field": "tag.value" } }
                                }
                              }

                  }
        }

CodePudding user response:

Try:

b = ["apple", "banana", "cherry"]

out = {
    "aggs": {
        fruit: {
            "filter": {"term": {"tag.name": fruit}},
            "aggs": {f"{fruit}_val": {"stats": {"field": "tag.value"}}},
        }
        for fruit in b
    }
}

print(out)

Prints:

{
    "aggs": {
        "apple": {
            "filter": {"term": {"tag.name": "apple"}},
            "aggs": {"apple_val": {"stats": {"field": "tag.value"}}},
        },
        "banana": {
            "filter": {"term": {"tag.name": "banana"}},
            "aggs": {"banana_val": {"stats": {"field": "tag.value"}}},
        },
        "cherry": {
            "filter": {"term": {"tag.name": "cherry"}},
            "aggs": {"cherry_val": {"stats": {"field": "tag.value"}}},
        },
    }
}
  • Related