Access custom object property while iterating over dictionary
you are iterating over a dictionary by looking at it keys and values.
But the values aren't strings but arrays of strings.
do
import Foundation
struct object {
var title:String?
}
var one = object(title:"green")
var two = object(title:"black")
var three = object(title:"blue")
var dict = ["a":[one, two], "b":[three]]
for (key, value) in dict {
for obj in value {
if let title = obj.title {
if title.lowercaseString.containsString(searchText.lowercaseString) {
// ...
}
}
}
}
iterate custom dictionary object
You can iterate over either the keys or the items of a dictionary:
Sub Tester()
Dim d As New Scripting.Dictionary
Dim k
d.Add "one", 1
d.Add "two", 2
d.Add "three", 3
For Each k In d.Keys
Debug.Print k
Next
For Each k In d.Items
Debug.Print k
Next
End Sub
So, you can expose your dictionary as a property of an object and iterate over that. It does mean you need to specify .Items
though (since it will default to keys.
How to iterate over a JavaScript object?
For iterating on keys of Arrays, Strings, or Objects, use for .. in
:
for (let key in yourobject) {
console.log(key, yourobject[key]);
}
With ES6, if you need both keys and values simultaneously, do
for (let [key, value] of Object.entries(yourobject)) {
console.log(key, value);
}
To avoid logging inherited properties, check with hasOwnProperty :
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) {
console.log(key, yourobject[key]);
}
}
You don't need to check hasOwnProperty
when iterating on keys if you're using a simple object (for example one you made yourself with {}
).
This MDN documentation explains more generally how to deal with objects and their properties.
If you want to do it "in chunks", the best is to extract the keys in an array. As the order isn't guaranteed, this is the proper way. In modern browsers, you can use
let keys = Object.keys(yourobject);
To be more compatible, you'd better do this :
let keys = [];
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) keys.push(key);
}
Then you can iterate on your properties by index: yourobject[keys[i]]
:
for (let i=300; i < keys.length && i < 600; i++) {
console.log(keys[i], yourobject[keys[i]]);
}
How to iterate over `dict` in class like if just referring to `dict`?
You'll have to implement the .keys()
, .values()
and .items()
methods yourself; together with __iter__
they can all delegate the actual work to the self.values()
dictionary:
class Klass:
def __init__(self, values):
self._values = values
self.more = None
def __getitem__(self, name):
return self._values[name]
def __iter__(self):
return iter(self._values)
def keys(self):
return self._values.keys()
def items(self):
return self._values.items()
def values(self):
return self._values.values()
I renamed the attribute to avoid masking the .values()
method.
The easiest way to delegate __iter__
to iteration over the dictionary (by key) is to use the iter()
function to get an iterator for the dictionary object.
To be explicit: __iter__
plays no role in how .keys()
, .values()
and .items()
are handled; the latter are just more methods.
Iterate over object attributes in python
Assuming you have a class such as
>>> class Cls(object):
... foo = 1
... bar = 'hello'
... def func(self):
... return 'call me'
...
>>> obj = Cls()
calling dir
on the object gives you back all the attributes of that object, including python special attributes. Although some object attributes are callable, such as methods.
>>> dir(obj)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo', 'func']
You can always filter out the special methods by using a list comprehension.
>>> [a for a in dir(obj) if not a.startswith('__')]
['bar', 'foo', 'func']
or if you prefer map/filters.
>>> filter(lambda a: not a.startswith('__'), dir(obj))
['bar', 'foo', 'func']
If you want to filter out the methods, you can use the builtin callable
as a check.
>>> [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj, a))]
['bar', 'foo']
You could also inspect the difference between your class and its instance object using.
>>> set(dir(Cls)) - set(dir(object))
set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__'])
Custom iterator for dictionary?
In C#3 and above you can use a (LINQ) extension method:
var myFilteredCollection = myCollection.Where( x => x.AmIIncludedInTheIteration );
foreach (var x in myFilteredCollection ) ...
Related Topics
Cannot Preview This File, App May Have Crashed -- Occurs When Inputting Specific Line of Code
Self. in Trailing Swift Closures, Meaning and Purpose
Need Explaining on the Double Label Function Declaration
Swift Can Not Save .M3U8 File to Gallery
Convert Integer to Roman Numeral String in Swift
How to Get Exactly the Same Point on Different Screen Sizes
Swift: Casting a Floatingpoint Conforming Value to Double
Calling a Child Inside 2 Levels of Nodes
What Does This Mean? Variable Declared Followed by a Block Without Assignment
Swift 3:Delegate Within Tapgesturerecognizer in Generics Doesn't Get Called
Swiftui - Navigation View Opening with Back Button and Half Grey Screen/Weird Behavior
Does _Arraytype or _Arrayprotocol Not Available in Swift 3.1
Custom Cell with Uitableview Inside Uicollectionviewcell
Requestaccessformediatype Doesn't Ask for Permission