a=Dict("x"=>1,"y"=>2,"z"=>3)b=Dict("w"=>10,"x"=>11,"y"=>2)println("Common keys:",intersect(keys(a),keys(b)))println("Keys in a not in b:",setdiff(keys(a),keys(b)))println("(key,value) pairs in common:",intersect(collect(a),collect(b)))Output:Commonkeys:Set(["x","y"])Keysinanotinb:Set(["z"])(key,value)pairsincommon:["y"=>2]
Extracting a subset from a dictionary
prices=Dict("ACME"=>46.23,"AAPL"=>612.78,"IBM"=>205.55,"HPQ"=>37.20,"FB"=>10.75,"INTL"=>30.56,"GS"=>322.3)# Make a dictionary of all prices over 100p100=Dict([(key,value)for(key,value)inpricesifvalue>100])println("All prices over 100")println(p100)# Make a dictionary of tech stockstech_shares=Set(["AAPL","IBM","HPQ","MSFT","INTL"])ptech=Dict([(key,value)for(key,value)inpricesifkeyintech_shares])println("All techs")println(ptech)Output:Allpricesover100Dict("IBM"=>205.55,"AAPL"=>612.78,"GS"=>322.3)AlltechsDict("HPQ"=>37.2,"IBM"=>205.55,"AAPL"=>612.78,"INTL"=>30.56)
portfolio=[Dict("name"=>"IBM","shares"=>100,"price"=>91.2),Dict("name"=>"AAPL","shares"=>50,"price"=>643.22),Dict("name"=>"FB","shares"=>150,"price"=>21.09),Dict("name"=>"HPQ","shares"=>35,"price"=>31.75),Dict("name"=>"YHOO","shares"=>45,"price"=>16.35),Dict("name"=>"ACME","shares"=>75,"price"=>115.65)]N=3sort(portfolio,by=x->x["price"])[1:N]#N smallest shares by pricesort(portfolio,by=x->x["price"],rev=true)[1:N]#N largest by price
Sort a dictionary to find minimum and maximum values
prices=Dict("ACME"=>45.23,"AAPL"=>612.78,"IBM"=>205.55,"HPQ"=>37.20,"FB"=>10.75)# Find min and max pricemin_price=findmin(prices)max_price=findmax(prices)println("min price: ",min_price)println("max price: ",max_price)println("sorted prices:")prices_sorted=sort(collect(prices),by=x->x[2])for(name,price)inprices_sortedprintln(" ",name," ",price)endOutput:minprice:(10.75,"FB")maxprice:(612.78,"AAPL")sortedprices:FB10.75HPQ37.2ACME45.23IBM205.55AAPL612.78
Sort a dictionary based on two keys simultaneously
rows=[Dict("fname"=>"Mohandas","lname"=>"Gandhi","uid"=>1003),Dict("fname"=>"Jawaharlal","lname"=>"Nehru","uid"=>1002),Dict("fname"=>"Narasimha","lname"=>"Rao","uid"=>1001),Dict("fname"=>"Arvind","lname"=>"Kejrival","uid"=>1004)]# sort list of Dicts by two keys simultaneouslya=sort(rows,by=x->(x["lname"],x["fname"]))print(a)Output:Dict("lname"=>"Gandhi","uid"=>1003,"fname"=>"Mohandas")Dict("lname"=>"Kejrival","uid"=>1004,"fname"=>"Arvind")Dict("lname"=>"Nehru","uid"=>1002,"fname"=>"Jawaharlal")Dict("lname"=>"Rao","uid"=>1001,"fname"=>"Narasimha")
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)