Flutter: Create map from list using a delimiter - list

I am trying to store a list of activities with a specific color locally and trying to convert the list into either a map or a list of lists.
Using shared preferences to save the data locally I have the following list:
List<String> value = ['Sleep: Blue', 'Meditation: Green', 'Running: Red'];
prefs.setStringList('ActivityList', value); //save data locally
But I want to be able to retrieve an object of the form:
values = [ {'Sleep', 'Blue'}, {'Meditation', 'Green'}, {'Running', 'Red'} ];
What would be the best way to do this and how would I use the delimiter ':' to split the data accordingly?
Thanks in advance!

I am not sure what you mean by array of objects. If you simply want an array of pairs, then the following should work for you
value.map((item) => item.split(": "))
Or if you want a key value map from your data, then you can do something like this:
Map.fromEntries(value.map((item) {
List<String> pair = item.split(": ");
return MapEntry(pair[0], pair[1]);
}));

Related

Merge 2 object lists in java

i have two lists listA and listB of type object
ListA[name=abc, age=34, weight=0, height=0] data collected from excel sheet
ListB[name=null, age=0, weight=70, height=6] data collected from database
Now i want to combine both the lists into a single list
MergedList[name=abc, age=34, weight=70, height=6]
Note: my obj class has more than 15 properties so adding each property one by one using getProperty() will be time-consuming.is there a better way?
Convert them to a Map where the key is the name of the object ( you denoting the elements as name=abc suggests they are name/value pairs ).
Map<String,MyMysteriousObject> converted = list.stream().collect( Collectors.toMap(MyMysteriousObject::getName, Function.identity() ) );
( replace the getName with what ever function you use to get the name of your object )
And then just merge the maps. How to merge maps is described here for example.
While at it, consider replacing the List with Map in your entire code. Will surely save a lot of work elsewhere too.
But if you have to have a list again, just List<MyMysteriousObject> resultList = new ArrayList<>(resultMap);

Looping through a list (with sublists) and assign the matching IDs to the same key and all of the corresponding values from that sublist?

I'm quite new in python coding and I canĀ“t solve the following problem:
I have a list with trackingpoints for different animals(ID,date,time,lat,lon) given in strings:
aList = [[id,date,time,lat,lon],
[id2,date,time,lat,lon],
[...]]
The txt file is very big and the IDs(a unique animal) is occuring multiple times:
i.e:
aList = [['25','20-05-13','15:16:17','34.89932','24.09421'],
['24','20-05-13','15:16:18','35.89932','23.09421],
['25','20-05-13','15:18:15','34.89932','24.13421'],
[...]]
What I'm trying to do is order the ID's in dictionaries so each unique ID will be the key and all the dates, times, latitudes and longitudes will be the values. Then I would like to write each individual ID to a new txt file so all the values for a specific ID are in one txt file. The output should look like this:
{'25':['20-05-13','15:16:17','34.89932','24.09421'],
['20-05-13','15:18:15','34.89932','24.13421'],
[...],
'24':['20-05-13','15:16:18','35.89932','23.09421'],
[...]
}
I have tried the following (and a lot of other solutions which didn't work):
items = {}
for line in aList:
key,value = lines[0],lines[1:]
items[key] = value
Which results in a key with the last value in the list forthat particular key :
{'25':['20-05-13','15:18:15','34.89932','24.13421'],
'24':['20-05-13','15:16:18','35.89932','23.09421']}
How can I loop through my list and assign the same IDs to the same key and all the corresponding values?
Is there any simple solution to this? Other "easier to implement" solutions are welcome!
I hope it makes sense :)
Try adding all the lists that match to the same ID as list of lists:
aList = [['25','20-05-13','15:16:17','34.89932','24.09421'],
['24','20-05-13','15:16:18','35.89932','23.09421'],
['25','20-05-13','15:18:15','34.89932','24.13421'],
]
items = {}
for line in aList:
key,value = line[0],line[1:]
if key in items:
items[key].append(value)
else:
items[key] = [value]
print items
OUTPUT:
{'24': [['20-05-13', '15:16:18', '35.89932', '23.09421']], '25': [['20-05-13', '15:16:17', '34.89932', '24.09421'], ['20-05-13', '15:18:15', '34.89932', '24.13421']]}

keys stored in list and using them in keyExtractor

I have a nested object and I extracted the keys and values using Object.keys and Object.values and storing them under 'keys' and 'arrayData' below. I can't figure out how to use keyExtractor with the list of keys ('keys') I have created to match the array. Any ideas?
nested object from firebase
let data = this.props.jobHistory
let keys = Object.keys(data)
let arrayData = Object.values(data)
<FlatList
keyExtractor={(item, index) => keys[index]} //I thought this would work but it is printing nothing
data={arrayData}
renderItem={({item}) => {
return (
<Text>{JSON.stringify(item)}{"\n"}</Text>
)}
}
Thanks
keyExtractor does not present or print any actual data, it only provides a "key" that's used by RN to differentiate components. It's an invisible value. Assuming every value in keys is unique, this should not return any errors. If you want to verify that the correct key is bring paired to the correct item when printed, you can do
keyExtractor={(item, index) => console.log(`${keys[index]}:${arrayData{index}}`);keys[index]} //I thought this would work but it is printing nothing

Loop through dict key equals to list than put in new list

I have a rather large dictionary right now that is set up like this:
largedict = {'journalname':{code: 2065},'journalname1':{code: 3055}}
and so on and so on. And another dictionary:
codes = {3055: 'medicine',3786: 'sciences'}
And I want to loop through largedict, compare it's code value to the keys in codes. Then either add all journalname key/value pairs that match the code to a different dictionary, or delete all that don't from largedict.
new_dic = {journal_name : journal_body for journal_name, journal_body in largedict.items() if journal_body["code"] in codes}

Scrapy/ item loader / How to load items in order?

I am trying to scrap the following a map coordinates , and I have the coordinates as var Data = {lat: 45.000000 , long : 68.00000}
I am able to scrap the above data items 'lng':68.0000 and 'lat':45.0000 as separate items.
and a also put them in a new Key "loc" as 'loc':{'lat':45.0000 ,long: 68.000000}. I am trying to store these scraped items in to MongoDb . In Mongodb ,I need the 'lng and 'lat' values ( coordinates) in a particular order So the Mongodb will recognize them as Geo locations. Mongodb needs 'lng' first and followed by 'lat'.
How do I do that?. Can some one help me?.
This is my Item file
class Citylist(scrapy.Item):
lng = scrapy.Field()
lat = scrapy.Field()
loc = scrapy.Filed()
This my spider file
for newlist in HtmlXPathSelector(response).select('/html/body'):
l = ItemLoader(item=Citylist(),response = response)
l.add_xpath('lng', '//......text()')
l.add_xpath('lat', '//......text()')
l.add_value('loc', {'lng': l.get_output_value('lng'),
'lat': l.get_output_value('lat')})
yield l.load_item()
My current out put is .....
'lng':'68.00000',
'lat':'45.00000',
'loc':{'lat':'45.00000','lng':'68.00000}.
1) I need my out put to be only .....
'loc':{'lng':'68.00000 ,'lat':'45.00000'},
I do not need .....
'lng':'68.00000', 'lat':'45.00000',
as separate values. Please advise how to do this
Thanks
First thing: here's a good answer about how to properly handle nested data in scrapy https://stackoverflow.com/a/25096896/2446893
Second thing: if order is important, you can use an OrderedDict https://docs.python.org/2/library/collections.html#collections.OrderedDict.
You can also use a tuple to return only the values, not the keys.