How to get element in specific index from NSMutable dictionary (Swift 3) - swift3

I need to get the first element from NSMutable dictionary. I tried to get the element using for loop. but I am not getting the correct element because the Dictionary does not follow order. Is there any way I can get the element?
Here is my code:
for (count, i) in myMutableDict.enumerated() {
if count == 2 {
print(i.key)
}
}

As you know dictionary is un ordered collection Type.
let dictionary:Dictionary = ["YYZ": "Toronto Pearson", "DUB": "Dublin"];
for(index,obj) in dictionary.enumerated() {
print("index- \(index) - Object- \(obj)");
print("key- \(obj.key) - value- \(obj.value)");
}
Enumeration will provide you index and Objects of dictionary as above code says. If you want to work with index then you need to get all keys and keep it sorted so that you can get your key by providing index. And from that key you can get value from dictionary object. Piece of code is given below.
var keyList = Array(dictionary.keys);
keyList = keyList.sorted();
print("keyList \(keyList)");
let keyAtIndex = keyList[1];
print("value = \(dictionary[keyAtIndex]!)");

Related

Python dictionary with tuples as key to new dictionary with keys as first element of tuple

I would like to convert the dictionary d1 to dictionary d2:
d1 = {('a','b'):1, ('a','c'):2, ('a','d'):3, ('b','c'):2, ('b','d'):1, ('c','f'):2, ('f','c'):2 }
d2 = {'a': [('b',1),('c',2) ,('d',3)], 'b':[('c',2),('d',1)], 'c':[('f',2)], 'f':[('c',2)]}
Can someone please tell me how to do this?
Just use for loop and loop through the dictionary, then make a new dictionary with your tuple first element as key
base = {('a','b'):1, ('a','c'):2, ('a','d'):3, ('b','c'):2, ('b','d'):1, ('c','f'):2, ('f','c'):2 }
newDict = {}
for key in base:
#Key is the tuple
if not key[0] in newDict.keys():
newDict[key[0]] = []
newDict[key[0]].insert(0, (key[1], base[key]))
print(newDict)
If you don't really care about the order of the list in new dictionary value, you should append instead of insert on 0 index, because insert on 0 index is slower than append.

How to iterate through single <key, value> pairs of List in dart

I have 2 Lists (uid and url) that are growable, and I need to set the first List as the key and the second as value. At some point, i'll have a 3rd List (randomUids) which will be keys and will print out the corresponding values. Here is the example code:
List<String> uid = ["uid1", "uid2","uid3","uid4"]; //Lists will grow larger after a while
List<String> url = ["url1","url2","url3","url4"];
List<String> randomUids = ["uid4", "uid2"];
When I try:
Map<List, List> mapKeyValue = Map();
mapKeyValue[uid] = url;
print( uid.contains(randomUids));
I get a false. Also, the print returns uid and url Lists as 2 long indices instead of separate Strings. How can I iterate the List so that url.contains(randomUids) is true. Also how can I print out the values of randomUids.
When I try:
print( uid.contains(randomUids));
I get a false.
Your code asks if uid (a List of Strings) contains randomUids (another List of Strings). It returns false because uid's elements are not Lists; they're Strings.
Presuming that you want the nth element of uid to correspond to the nth element of url, and you can guarantee that uid.length == url.length, you can construct a Map of UIDs to URLs:
assert(uid.length == url.length);
var uidMap = <String, String>{
for (var i = 0; i < uid.length; i += 1)
uid[i]: url[i],
};
And then you can iterate over randomUids and do lookups:
for (var uid in randomUids) {
if (uidMap.containsKey(uid)) {
print(uidMap[uid]);
}
}

Can I assign position of item in list?

ex = ['$5','Amazon','spoon']
I want to re-order this list, website - item - price.
Can I assign the index, for instance, ex.index('Amazon') = 1?
I'd like the result to be ['Amazon','spoon','$5']
I found information on how to swap positions, but I would like to know if I can assign an index for each item myself.
You cannot assign an index to an item, but you can build a permuted list according to a permutation pattern:
ex = ['$5','Amazon','spoon']
order = [1, 2, 0]
ex_new = [ex[i] for i in order]
print(ex_new)
#['Amazon', 'spoon', '$5']
Alternatively, you can overwrite the original list in place:
ex[:] = [ex[i] for i in order]
print(ex)
#['Amazon', 'spoon', '$5']

How to get value from list using index?

I have to try to get one by one value from list using index and i have try to get index value and update my stage one by one and respectively.
my python code below :
for ress in status_list:
print"res", ress
#self.workflow_stages = ress
if ress:
self.workflow_stages = ress
for index, item in enumerate(status_list):
print "test::", index
index_init = index
print"index_init:::", index_init
next = index_init + 1
print "next", next
lent = len(status_list)
print"lent", lent
return True
Thanks.
This for index, item in enumerate(status_list): means that index variable holds your respective index of the status_list and item variable holds your value. So in given for loop, item will hold the value of the corresponding index.
Generally, if you don't use the enumerate functionality to iterate over a list, you can access a value of the list like this status_list[index]

How to get the value of one element in a List in groovy/grails

After do a createCriteria query, I have a object list of only 1 item with 7 strings inside. That I want to do is get only one of this seven elements??
List<Object> result - com.test.MyService.getConfig(String, String, String, String, String, String, String)
This are the elements that I get in the list:
[name:John, surname:John city:Rome, car:BMW, country:Italy, day:Monday, color:Red,]
I want access for example only to get the string 'country' to can return it in a method:
I'm trying to do this:
result.get(4)
And I'm gettin this error:
java.lang.IndexOutOfBoundsException: Index: 4, Size: 1
Try
def oneObject = YourDomainClass.createCriteria().get{
//add your criteria if any
}
return oneObject.country
You get java.lang.IndexOutOfBoundsException: Index: 4, Size: 1 because when you execute YourDomainClass.createCriteria().list{} you get a list of YourDomainClass objects (which has only one object). So if you want to use YourDomainClass.createCriteria().list{} you should execute:
def objects = YourDomainClass.createCriteria().list{}
if(objects) //check if any object is in list
return objects[0].country
What you can do is:
Either just do result.first().country
Or if you are sure that criteria will return a single result always then use get instead of list.
And if you just need a single property then use projection to fetch that property only instead of whole object.
def result = DomainClass.createCriteria().list { //or get
resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
projections {
property("country", "country")
}
}
In this case when using .list{} to get value for country:
With result transformer return result.first().country
Without result transformer: return result.first()
When using .get{} instead of .list{}:
With result transformer return result.country
Without result transformer: return result