Python:如何在列表内的字典中获取id字段

时间:2019-05-15 08:47:03

标签: python list dictionary

我想获取满足条件的dict的ID(如果当前日期在任何时间表上)

folder <- "C:/Users/user/Desktop/R/test/"

jpeg  <- basename(list.files(folder, pattern= "\\.jpeg$", recursive = TRUE))
train <- paste0("data/obj/", jpeg)

write.table(train, "train.txt", sep="", row.names = FALSE, col.names = FALSE, quote = FALSE)

我尝试过:

arr = [
  {
    "schedule": "Mon - Wed - Fri",
    "id": 1
  },
  {
    "schedule": "Mon - Tue - Wed - Thu - Fri",
    "id": 2
  },
  {
    "schedule": "Fri - Sat - Sun",
    "id": 3
  },
  {
    "schedule": "Mon - Wed - Fri - Sat",
    "id": 4
  },
  {
    "schedule": "Sat - Sun - Mon - Tue",
    "id": 5
  }
]

我得到:

day = "Wed"

for listArr in arr:
    array = listArr.values()
    str1 = " - ".join(array)
    strArr = str1.split(" - ")

    if any(day in i for i in strArr):
        print(strArr)

我想要什么:

TypeError: sequence item 1: expected string, int found

我试图将int转换为str,但是它返回null或空白。有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

day = "Wed"
print([l['id'] for l in arr if day in l['schedule']])

答案 1 :(得分:0)

您正在做的事情比需要做的要困难得多。您只需要获取列表中每个项目的id值即可。

所以:

for item in arr:
    if day in item['schedule']
        print(item['id'])

尽管您需要收集ID而不是仅打印ID,但列表理解会更好:

result = [item['id'] for item in arr if day in item['schedule']]