我需要的是如何过滤NSDictionary
并仅返回键包含字符串的值和键
例如,如果我们NSDictionary
包含:
{
"houssam" : 3,
"houss" : 2,
"other" : 5
}
,字符串为"houss"
所以我们需要返回
{
"houssam" : 3,
"houss" : 2
}
最诚挚的问候,
答案 0 :(得分:2)
您可以使用filter
功能以下列方式获取所需内容:
var dict: NSDictionary = ["houssam": 3, "houss": 2, "other": 5 ]
let string = "houss"
var result = dict.filter { $0.0.containsString(string)}
print(result) //[("houssam", 3), ("houss", 2)]
上面的代码返回一个元组列表,如果你想再次获得一个[String: Int]
字典,你可以使用以下代码:
var newData = [String: Int]()
for x in result {
newData[x.0 as! String] = x.1 as? Int
}
print(newData) //["houssam": 3, "houss": 2]
我希望这对你有所帮助。
答案 1 :(得分:1)
使用此代码获取匹配的密钥。
var predicate = NSPredicate(format: "SELF like %@", "houss");
let matchingKeys = dictionary.keys.filter { predicate.evaluateWithObject($0) };
然后只需获取哪些键位于matchingKeys
数组中。
答案 2 :(得分:0)
由于这是一个NSDictionary,您可以在键数组上使用let data: NSDictionary = // Your NSDictionary
let keys: NSArray = data.allKeys
let filteredKeys: [String] = keys.filteredArrayUsingPredicate(NSPredicate(format: "SELF CONTAINS[cd] %@", "houss")) as! [String]
let filteredDictionary = data.dictionaryWithValuesForKeys(filteredKeys)
方法,并从初始字典中获取值。
例如:
from tkinter import *
#DATA
class Staff(object):
def __init__(self, name, ID):
self.name = name #this data comes from storage
self.ID = ID #this is for this instance, starting from 0 (for use with grid)
ID42 = Staff("Joe", 0)
ID25 = Staff("George", 1)
ID84 = Staff("Eva", 2)
stafflist = [ID42, ID25, ID84]
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
scheduleDictionary = {}
for r in range(0,3):
scheduleDictionary[r] = ['shift','shift','shift','shift','shift','shift','shift','shift','shift','shift','shift','shift','shift','shift']
#Build window
root = Tk()
ScheduleFrame = Frame(root)
ScheduleFrame.pack()
#(Re)Build schedule on screen
def BuildSchedule():
for r in range(1,4):
Label(ScheduleFrame, text=stafflist[r-1].name).grid(row=r, column=0)
for c in range(1,15):
Label(ScheduleFrame, text=weekdays[(c-1)%7]).grid(row=0, column=c)
for r in range(1,4):
for c in range(1,15):
Label(ScheduleFrame, text=scheduleDictionary[r-1][c-1]).grid(row=r, column=c)
#Mouse events
def mouse(event):
y = event.widget.grid_info()['row'] - 1
x = event.widget.grid_info()['column'] - 1
print(x,y)
shiftSelection(y,x)
#shiftSelection
def shiftSelection(row, column):
shifts_window = Tk()
box = Listbox(shifts_window)
box.insert(1, "MR")
box.insert(2, "AR")
box.insert(3, "ER")
box.pack()
button = Button(shifts_window, text="Okay", command = lambda: selectShift(shifts_window, box.get(ACTIVE),row, column))
button.pack()
def selectShift(shifts_window, shift,row, column):
scheduleDictionary[row][column] = shift
BuildSchedule()
shifts_window.destroy()
root.bind("<Button-1>", mouse)
BuildSchedule()
root.mainloop()
希望有所帮助。