简体   繁体   English

将元组添加到嵌套字典中的列表

[英]Adding tuples to lists in nested dictionaries

I would like to add a tuple to a list for data that I already have in a nested dictionary format if it is missing.我想将一个元组添加到我已经以嵌套字典格式拥有的数据的列表中,如果它丢失的话。

all_cap = {"cap_1":{"id":1001, "vitals":[("Temp", 101), ("HR", 60)]}, "cap_2": 
{"id":1002, "vitals":[("Temp", 104), ("HR", 60), ("RR", 12)]}}

So, if I went to add a tuple ("RR", 16) to cap_1 it would work, but if I wanted to add it to cap_2 it would not overwrite the RR that is already there or even add the second RR to it.所以,如果我去向 cap_1 添加一个元组 ("RR", 16) 它会起作用,但如果我想将它添加到 cap_2 它不会覆盖已经存在的 RR,甚至不会向其中添加第二个 RR。 I've tried going in to it like this:我试过这样进入它:

def add_vital(dict, str, int):
  if all_cap[dict]["vitals"][0][0:len("vitals")] == str:
    return True
  else:
    all_caps[dict]["vitals"].append(str, int)
    return False

I know that I have been asking quite a few questions on here today, and I truly do appreciate the answers I have received.我知道我今天在这里问了很多问题,我真的很感激我收到的答案。 It has been helping, but I just started trying to do some work in Python today (before now, I have only used R), so getting up and running with some of it has been daunting.它一直在帮助,但我今天才开始尝试在 Python 中做一些工作(在此之前,我只使用过 R),因此启动和运行其中的一些工作令人生畏。

You can do this with lists of tuples by searching over them, but based on usage it really seems like these should just be dicts of dicts.您可以通过搜索元组列表来执行此操作,但根据使用情况,看起来这些应该只是 dicts 的 dicts。

all_cap = { 
    "cap_1": { "id": 1001, "vitals": {
        "Temp": 101, 
        "HR": 60,
    }},
    "cap_2": { "id": 1002, "vitals": {
        "Temp": 104,
        "HR": 60,
        "RR": 12,
    }},
}

Now your add_vital function is just:现在您的add_vital function 只是:

def add_vital(cap_id, vital, value):
    # type: (str, str, int) -> bool
    if vital in all_cap[cap_id]["vitals"]:
        return True
    else:
        all_cap[cap_id]["vitals"][vital] = value
        return False

Given the structure you've got, I think you need something more like:鉴于您拥有的结构,我认为您需要更多类似的东西:

def add_vital(cap_id, vital, value):
    # type: (str, str, int) -> bool
    if any([vital_pair[0] == vital 
            for vital_pair in all_cap[cap_id]["vitals"]]):
        return True
    else:
        all_cap[cap_id]["vitals"].append((vital, value))
        return False

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM