简体   繁体   English

Python:如何在通过循环创建的字典中添加额外的项目?

[英]Python: How can I add extra item in dictionary created via a loop?

I'm creating a table like this:我正在创建一个这样的表:

data = json.load(f)
num_of_certificates = (len(data.get('certificates')))
new_data = sorted([{n: f"{data.get('certificates', [{}])[i].get(n, 0)}"
                        for n in some_dic}
                      for i in range(num_of_items)], key=lambda x: (int(x['exp_date_year']), int(x['exp_date_month']), int(x['exp_date_day'])))

and I want to add an extra item.我想添加一个额外的项目。 Imagine having one more "n" to loop through but I can't just add it in the "some_dic" for my reasons that dont affect this.想象一下还有一个“n”要循环,但我不能将它添加到“some_dic”中,因为我的原因不会影响这一点。 I tried我试过了

data = json.load(f)
num_of_certificates = (len(data.get('certificates')))
new_data = sorted([{n: f"{data.get('certificates', [{}])[i].get(n, 0)}",
                    'test': 'test value'
                        for n in some_dic}
                      for i in range(num_of_items)], key=lambda x: (int(x['exp_date_year']), int(x['exp_date_month']), int(x['exp_date_day'])))

but it doesn't work.但它不起作用。 I made it work doing it like this:我让它像这样工作:

data = json.load(f)
num_of_certificates = (len(data.get('certificates')))
new_data = sorted([{n: f"{data.get('certificates', [{}])[i].get(n, 0)}" if n is not "remaining_days" else "new_value"
                        for n in some_dic}
                      for i in range(num_of_certificates)], key=lambda x: (int(x['exp_date_year']), int(x['exp_date_month']), int(x['exp_date_day'])))

basically adding another empty thing inside "some_dic" but this creates other issues and I feel like there's a way easier way to do this.基本上在“some_dic”中添加了另一个空的东西,但这会产生其他问题,我觉得有一种更简单的方法可以做到这一点。 Here's the "some_dic" dictionary这是“some_dic”字典

    some_dic = {
    "name": False,
    "type": False,
    "exp_date_day": False,
    "exp_date_month": False,
    "exp_date_year": False,
    "color": False,
    "remaining_days": True
     }

Here's the json file im parsing:这是正在解析的 json 文件:

{
  "certificates": [
    {
      "exp_date_year": "2020",
      "name": "1",
      "type": "1",
      "exp_date_day": "1",
      "exp_date_month": "1",
      "color": "1",
      "exp_date_day_of_year": 1
    },
    {
      "exp_date_year": "2020",
      "name": "2",
      "type": "2",
      "exp_date_day": "2",
      "exp_date_month": "2",
      "color": "2",
      "exp_date_day_of_year": 33
    },
    {
      "exp_date_year": "2022",
      "name": "3",
      "type": "3",
      "exp_date_day": "3",
      "exp_date_month": "3",
      "color": "3",
      "exp_date_day_of_year": "62"
    }
  ]
}

First, you should probably une regular loops to avoid an overcomplicated expression like this.首先,您可能应该取消常规循环以避免像这样过于复杂的表达式。

Second, your f-string make no sense:其次,你的f-string没有意义:

f"{data.get('certificates', [{}])[i].get(n, 0)}"

is the same as:是相同的:

str(data.get('certificates', [{}])[i].get(n, 0))

Third, you can replace:三、可以更换:

[{n: str(data.get('certificates', [{}])[i].get(n, 0)})
    for n in some_dic}
    for i in range(num_of_items)]

By:经过:

[{n: str(c.get(n, 0)})
    for n in some_dic}
    for c in data.get('certificates', [{}])]

Because c will iterate over the elements of data['certificates'] .因为c将遍历data['certificates']的元素。

Fourth, since you are using only the keys of some_dic , you can write:第四,由于您只使用some_dic的键,您可以编写:

some_keys = {"name", "type", "exp_date_day", "exp_date_month", "exp_date_year", "color"}
L = [{n: str(c.get(n, 0)})
    for n in some_keys}
    for c in data.get('certificates', [{}])]
new_data = sorted(L, ...)

Fifth, I would test if certificates is in data before the list comprehension.第五,我会在列表理解之前测试certificates是否在data中。 Note that you return an empty list if data['certificates'] is an empty list or if the key certificates is not in data .请注意,如果data['certificates']是一个空列表或密钥certificates不在data中,则返回一个空列表。 I would rather raise an error in the second case:我宁愿在第二种情况下提出错误:

if 'certificates' not in data:
    raise ValueError("Data is corrupted")
certificates = data['certificates']
L = [{k: str(c.get(n, 0)}) for k in some_keys} for c in certificates]
...

And sixth, the actual answer to your question , you want to add an element to the dict in one expression.第六,您问题的实际答案,您想在一个表达式中向 dict 添加一个元素。 See this question and the answers:请参阅此问题和答案:

L = [{**{k: str(c.get(n, 0)}) for k in some_keys}, 'remaining_days': 'new_value'} for c in certificates]

Again, prefer regular loops unless this part of your code is a bottleneck.同样,除非这部分代码是瓶颈,否则更喜欢常规循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将一个字典中的值作为项目合并到在“for”循环中创建的另一个字典? - How can I merge values in one dictionary as an item to another dictionary created inside a "for" loop? 如何在python字典中分析列表值,添加额外的字典值来显示不同的键和共同的列表值计数? - How can I analyze list values in a python dictionary, add extra dictionary values showing the different keys and the list value count in common? 如何通过循环将变量添加到字典中? - How can I add variables into a dictionary with a loop? 如何在Python中向字典添加字符串? - How can I add a string to a dictionary in Python? Scrapy / Python:如何将项目添加到在类内部创建的列表中? - Scrapy / Python: How can I add an item to a list created inside a class? 如何在现有字典中添加字典,Python - How can I add a dictionary inside an existing dictionary ,Python 如何添加带有按钮的新条目字段? 条目字段由 Python Tkinter 中的循环创建 - How can I add a new Entry field with a Button? The Entry field was created by a loop in Python Tkinter 当我在python中循环时如何添加字典项 - How to add dictionary items when I loop in python 如何使用for循环将新条目添加到python字典? - How do I use a for loop to add new entries to a python dictionary? 如何将方法用作字典中的项目? Python 2.x - How can I use a method as a item in a dictionary? Python 2.x
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM