This is my code example:
budi = {"Name" : "Budi", "Gender" : "Male", "Age" : 18}
ahmad = {"Name" : "Ahmad", "Gender" : "Male", "Age" : 7}
ika = {"Name" : "Ika", "Gender" : "Female", "Age" : 18}
marged = [budi, ahmad, ika]
I want the results like this, for example based on the 18 year old:
The oldest participants are: Budi and Ika
Here is the code according to what have you asked in the question. Please go through this very simple implementation.
from operator import itemgetter
budi = {"Name" : "Budi", "Gender" : "Male", "Age" : 1}
ahmad = {"Name" : "Ahmad", "Gender" : "Male", "Age" : 7}
ika = {"Name" : "Ika", "Gender" : "Female", "Age" : 18}
marged = [budi, ahmad, ika]
newlist = sorted(marged, key=itemgetter('Age'), reverse=True)
maxAge = newlist[0]["Age"]
finalList = [newlist[0]["Name"]]
for person in newlist[1:]:
if person["Age"] == maxAge:
finalList.append(person["Name"])
if len(finalList) == 1:
print "The oldest participant is: " + finalList[0]
else:
print "The oldest participants are: ",
for name in finalList:
print name+" ",
Related
I'm trying to filter a query with term and range along with query-string. filter(range) and query string works but not filter(term). am i doing something wrong?
es = Elasticsearch([{'host': '192.168.121.121', 'port': 9200}])
index = Index("filebeat-*",using=es)
search = index.search()
searchStr = "OutOfMemoryError"
search = search.query("query_string", query=searchStr)
search = search.filter('range' , **{'#timestamp': {'gte': 1589399137000 , 'lt': 1589399377000, 'format' : 'epoch_millis'}})
search = search.filter('term' , **{'can.deployment': 'can-*' })
response = search.execute(ignore_cache=True)
print(response.hits.total)
print(response.hits.hits._source.can.deployment)
json:
filter-term - ['hits']['hits']['_source']['can']['deployment']
filter-range- ['hits']['hits']['_source']['#timestamp']
{
"hits" : {
"total" : 138351328,
"max_score" : 6.5700893,
"hits" : [
{
"_index" : "filebeat-6.1.2-2020.05.13",
"_type" : "doc",
"_score" : 2.0166037,
"_source" : {
"#timestamp" : "2020-05-13T01:14:03.354Z",
"source" : "/var/log/gw_rest/gw_rest.log",
"message" : "[2020-05-13 01:14:03.354] WARN can_gw_rest [EventLoopGroup-3-2]: An exceptionCaught() event was fired.OutOfMemoryError,
"fileset" : {...},
"can" : {
"level" : "WARN",
>>>>>>>> "message" : "An exceptionCaught() event was fired- OutOfMemoryError,
"timestamp" : "2020-05-13 01:14:03.354",
>>>>>>>> "deployment" : "can-6b721b93965b-w3we4-4074-9903"
}
}
}
]
}
}
I actually didn't need a filter(term). this worked:
dIds=response['hits']['hits'][1]['_source']['can']['deployment']
print(dIds)
#loop through the response
for i in response['hits']['hits']:
id = i['_source']['can']['deployment']
print(id)
Suppose I have two lists of objects
List1 = [{"name" : "Mac", "age":24, "id" : 1},
{"name" : "Mona","age":22, "id" : 2}]
and
List2 = [{"type" : "human","country":"AUS"}]
How do I append all elements from List 2 to all the elements of list 1
so that the final list1 would look like
[{"name" : "Mac", "age":24, "id" : 1, "type" : "human","country":"AUS"},{"name" : "Mona", "age":22, "id" : 2, "type" : "human","country":"AUS"}]
Currently am looping through and doing an update on list which is working but I want to know if there's an easier and better way to do this
for person in List1:
person.update(List2)
print List1
List1 = [{"name" : "Mac", "age":24, "id" : 1},
{"name" : "Mona","age":22, "id" : 2}]
List2 = [{"type" : "human","country":"AUS"}]
List1 = List1 + List2
This will work, I've checked in Python 2.7. Hope this answer helps.
You can also try below code-
List1 = [{"name" : "Mac", "age":24, "id" : 1},
{"name" : "Mona","age":22, "id" : 2}]
List2 = [{"type" : "human","country":"AUS"}]
finalList = [dict(l.items() + List2[0].items()) for l in List1]
print finalList
How to add dictionary's key, value in array as array index form, like this
[
{
"summary": "fdsfvsd"
},
{
"content_date": "1510158480"
},
{
"content_check": "yes"
}
]
As per your question, you want to work with array of dictionaries in Swift,
here is the simple way to achieve the same :
var arrayOfDict = [[String: String]]()
//creating dictionaries
let dict1 = ["name" : "abc" , "city" : "abc1"]
let dict2 = ["name" : "def" , "city" : "def1"]
let dict3 = ["name" : "ghi" , "city" : "ghi1"]
let dict4 = ["name" : "jkl" , "city" : "jkl1"]
//Appending dictionaries to array
arrayOfDict.append(dict1)
arrayOfDict.append(dict2)
arrayOfDict.append(dict3)
arrayOfDict.append(dict4)
//accessing each and every element of the arrayOfDictionary
for dict in arrayOfDict{
for (key, value) in dict {
print("the value for \(key) is = \(value)")
}
}
Hope it helps you!
I'm having problem storing lists of embedded documents/objects in MongoDB using the Grails MongoDB plugin. I used the information given in the documentation in chapter 3 but only got the embedding of one object working.
For testing purposes I created two domain objects Person and Address in a new Grails project. They look like this:
class Person {
ObjectId id
String firstName
String lastName
Address address
List otherAddresses = []
static embedded = ['address', 'otherAddresses']
}
class Address {
String street
String postCode
String city
}
When I execute the following lines in Bootstrap.groovy it stores two Person objects in MongoDB - both have a correct address but in person1 the otherAddresses List is "[ null ]" and in person2 the otherAddresses List is "[ { "street" : "Second Street. 164" , "city" : "New York" , "postCode" : "13579"}]"
def address = new Address(street: "Mainstreet. 164", city: "New York", postCode:"12345")
def person1 = new Person(firstName: "John", lastName: "Doe")
person1.address = address
person1.otherAddresses.add(address)
println person1.otherAddresses // Result: "[mongoembeddedlisttest.Address : (unsaved)]"
person1.save()
person1.errors.allErrors.each { println it } // no errors
def person2 = new Person(firstName: "Jane", lastName: "Doe")
person2.otherAddresses += ['street': 'Second Street. 164', 'city': 'New York', 'postCode':'13579']
println person2.otherAddresses // Result: "[[street:Second Street. 164, city:New York, postCode:13579]]"
person2.save()
Resulting Database Entries:
{ "_id" : { "$oid" : "521089461a150b20390d61c2"} , "address" : { "city" : "New York" , "postCode" : "12345" , "street" : "Mainstreet. 164"} , "firstName" : "John" , "lastName" : "Doe" , "otherAddresses" : [ null ] , "version" : 0}
{ "_id" : { "$oid" : "521089461a150b20390d61c3"} , "firstName" : "Jane" , "lastName" : "Doe" , "otherAddresses" : [ { "street" : "Second Street. 164" , "city" : "New York" , "postCode" : "13579"}] , "version" : 0}
Further Notes:
I'm using a pure mongodb approach (no a hybrid together with Hibernate)
I'm working on a Windows 8 machine using Grails 2.2.1 running mongo db 2.4.4
Person is a domain object in /grails-app/domain and Address is a "normal" groovy class in /src/groovy (I can put it in domain folder but that has no effect)
Everything is set to be nullable in Config.groovy: grails.gorm.default.constraints = { '*'(nullable: true) }
BuildConfig.groovy has the plugin entry: compile ":mongodb:1.3.0"
What am I doing wrong? How can I store a list of embedded objects using the Grails mechanism?
I think you're adding a map in the second person instead of an Address object. Is there any reason why you're adding the otherAddress different for each person?
I think this should work although I haven't tested it:
def address = new Address(street: "Mainstreet. 164", city: "New York", postCode:"12345")
def person1 = new Person(firstName: "John", lastName: "Doe")
person1.address = address
person1.otherAddresses.add(address)
println person1.otherAddresses // Result: "[mongoembeddedlisttest.Address : (unsaved)]"
person1.save()
person1.errors.allErrors.each { println it } // no errors
def person2 = new Person(firstName: "Jane", lastName: "Doe")
person2.otherAddresses += new Address('street': 'Second Street. 164', 'city': 'New York', 'postCode':'13579')
println person2.otherAddresses
person2.save()
I have a list of meeting rooms with the following capacity of people they support. The data is something like:
{
"name" : "Room 1",
"city" : "Mumbai",
"capacity" : 4
},
{
"name" : "Room 2",
"city" : "Mumbai",
"capacity" : 10
},
{
"name" : "Room 3",
"city" : "Mumbai",
"capacity" : 6
},
{
"name" : "Room 6",
"city" : "Mumbai",
"capacity" : 3
},
{
"name" : "Room 4",
"city" : "Mumbai",
"capacity" : 2
}
// etc etc
Now I want to add a filter so that when I choose the number of ppl that need to meet the app shows me all rooms having a capacity GREATER THAN this number.
For example: If I say I'm looking for a room for 4 ppl it should show me room 1,2,3. If I search for a room for 2 ppl it shows all the rooms. Etc.
As of now if I use a filter this is what I do now:
store.filter("capacity",2)
and it only shows me rooms with the capacity of 2. Not rooms with a greater capacity.
What should I do???
You need to create a filter function like this:
var roomFilter = new Ext.util.Filter({
filterFn: function(item) {
return item.capacity > 2;
}
});
then:
var largeRooms = store.filter(roomFilter);
P/S: If Ext.util.Filter doesn't work with your Store, you should create a clone of its data which is of type Ext.util.MixedCollection.