convert the value of dictionary from list to float - python

I have a dictionary named "location" like this:
{
'WA': [
'47.3917',
'-121.5708'
],
'VA': [
'37.7680',
'-78.2057'
],
...
}
I want to convert to a dic that the value is a float, so it looks like:
{
'WA': [
47.3917,
-121.5708
],
'VA': [
37.7680,
-78.2057
],
...
}
I tried
for key in location.keys():
location[key] = float(location[key][0,1])
print location
it gives me an arror that "float() argument must be a string or a number"
how can I fix that?

You can use dictionary comprehension to construct a dictionary which has the values converted to floats, like this
print {k:map(float, locations[k]) for k in locations}
As suggested by #Grijesh in the comments section, if you are using Python 3,
print({k:list(map(float, locations[k])) for k in locations})

Your problem is in here: float(location[key][0,1])
# float objects are length 1
for key in location.keys():
location[key] = [float(location[key][0]),float(location[key][1])]
print location

You can use a list comprehension within a dictionary comprehension. Since you need both keys and values, use dict.items to iterate key-value pairs:
res = {k: [float(x) for x in v] for k, v in locations.items()}
map works more efficiently with built-ins, so you may wish to use:
res = {k: list(map(float, v)) for k, v in locations.items()}
Or, since you have coordinates, for tuple values:
res = {k: tuple(map(float, v)) for k, v in locations.items()}
The problem with your logic location[key][0,1] is Python lists do not support vectorised indexing, so you need to be explicit, e.g. the verbose [float(location[key][0]), float(location[key][1])].

Related

How do I add multiple tuples and convert into only list

I got confused between Representations. But I checked, my output is "class tuple"
My code is:
for key, value in analysis.items():
tvi = (key, {k:v for k, v in value.indicators.items() if k in indica})
TVA = print(tvi)
And I had a list of multiple tuples:
('James',{'hair':'black','eye':'brown'})
('Michael',{'hair':'brown','eye':None})
('Robert',{'hair':'red','eye':'black'})
('Washington',{'hair':'grey','eye':'grey'})
('Jefferson',{'hair':'brown','eye':''})
I want to convert into a big list like that:
[
('James',{'hair':'black','eye':'brown'}),
('Michael',{'hair':'brown','eye':None}),
('Robert',{'hair':'red','eye':'black'}),
('Washington',{'hair':'grey','eye':'grey'}),
('Jefferson',{'hair':'brown','eye':''})
]
You can do this with list comprehension,
[(key, {k:v for k, v in value.indicators.items() if k in indica})
for key, value in analysis.items()]

Find item in list of dicts

I have a list of dictionary something like this:
list = [
{
"ENT_AUT":[
"2018-11-27"
]
},
{
"ENT_NAT_REF_COD":"C87193"
},
{
"ENT_NAM":"MONEYBASE LIMITED"
},
{
"ENT_NAM_COM":"MONEYBASE LIMITED"
},
{
"ENT_ADD":"Ewropa Business Centre, Triq Dun Karm"
},
{
"ENT_TOW_CIT_RES":"Birkirkara"
},
{
"ENT_POS_COD":"BKR 9034"
},
{
"ENT_COU_RES":"MT"
}
]
Here every dictionary will always contain only one key value pair. Now I need to know the value of ENT_NAM, ENT_AUT and etc all fields.
I tried something like this:
ENT_NAM = (list[2].values())[0]
print('ENT_NAM = ', ENT_NAM)
It works perfectly for this list but my problem is that the 'ENT_NAM' containing dictionary will not always be on the 2nd index of the list. How can I generalize this solution so that even if the order of the dictionary under the list changes, I always find a perfect solution?
What you are describing is a search problem. Here the naive solution is probably fine:
def get_prop(dicts, k):
return next(x[k] for x in dicts if k in x)
get_prop(l, "ENT_NAM")
Incidentally, don't call your variable list: it shadows a builtin.
If you need to use this data more than about 3 times I would just reduce it to a dict:
def flatten(dicts):
iterdicts = iter(dicts)
start = next(iterdicts)
for d in iterdicts:
start.update(d)
return start
one_dict = flatten(list_of_dicts)
one_dict["ENT_NAM"]
(There are plenty of other ways to flatten a list of dicts, I just currently think the use of iter() to get a consumable list is neat.)
As jasonharper said in the comments, if it is possible, the data should be formulated as a single dictionary.
If this cannot happen, you can retrieve the value of ENT_NAM using:
print(list(filter(lambda elem: "ENT_NAM" in elem.keys(), my_list))[0]["ENT_NAM"])
Returns:
MONEYBASE LIMITED
Note: list has been renamed to my_list since list is a reserved Python keyword
If all of the keys are unique, you can flatten the list of dictionaries into a dictionary with a straightforward dictionary comprehension.
Note: you don't want to use list as a name for a variable, as it is an important built-in type. Use something like lst instead.
{ k: v for d in lst for k, v in d.items() }
Result:
{'ENT_AUT': ['2018-11-27'], 'ENT_NAT_REF_COD': 'C87193',
'ENT_NAM': 'MONEYBASE LIMITED', 'ENT_NAM_COM': 'MONEYBASE LIMITED',
'ENT_ADD': 'Ewropa Business Centre, Triq Dun Karm',
'ENT_TOW_CIT_RES': 'Birkirkara', 'ENT_POS_COD': 'BKR 9034',
'ENT_COU_RES': 'MT'}
Getting the value for key 'ENT_NAM' is now just:
{ k: v for d in lst for k, v in d.items() }['ENT_NAM']

Best way to substitute both K&V based on a map?

Let say we have a map-dict and data-dict :
m = { 1:2, 4:5, 3:7 }
data = { 1:7, 4:1, 3:6 }
we should replace all occurrences both key&val in "data" according to "m" :
data1 = { 2:7, 5:2, 7:6 }
what is the shortest, fast way to do this ?
I was thinking of converting data to list do the replacements and convert back to dict. But even that gets too involved.
Converting list to dict is OK :
dict(zip(lst[0::2], lst[1::2]))
Converting dict to list is :
data.items()
but this one does not return list, but list of tuples, which make things too involved i.e we need to additionally flatten this LoT.
I was wondering if there is a better way, with emphasis on speed/mem.
dict comprehension:
data1 = {m.get(k, k): m.get(v, v) for k, v in data.items()}
Note that {4: 1, 4: 6} in your example is a single element.

Create a new dict of first n values (and keys) from dictionary - Python

I have a dictionary:
{'my_account': [45010045, 43527907, 45147474, 35108100, 45159973],
'your_account': [38966628, 28171579, 39573751, 41359842, 42445236],
'his_account': [44822460, 45010045, 39276850, 39896128, 45265335]
}
I want to keep the first 2 elements of every key, so the result would look like:
{'my_account': [45010045, 43527907],
'your_account': [38966628, 28171579],
'his_account': [44822460, 45010045]
}
Is there any way to achieve this? Thanks.
using dictionary comprehension
my_dict = {'my_account': [45010045, 43527907, 45147474, 35108100, 45159973],
'your_account': [38966628, 28171579, 39573751, 41359842, 42445236],
'his_account': [44822460, 45010045, 39276850, 39896128, 45265335]
}
new_dict = {k:v[:2] for k,v in my_dict.items()}
# {'my_account': [45010045, 43527907], 'your_account': [38966628, 28171579], 'his_account': [44822460, 45010045]}
Just slice-delete the values.
for v in D.itervalues():
del v[2:]

using python - grab only particular values from key:value pairs in parsed JSON

I am trying to extract particular data from a JSON file. Here is my code.
jsonurl = http://localhost:8080/test.json
a = urllib2.urlopen(jsonurl).read()
b = json.loads(a)
for x, y in b.iteritems():
print x, y
here is my json
{
"abc": [
"build=1.0.44.0",
"proxy=none"
],
"xyz": [
"proxy=https",
"build=1.0.127.0"
],
"alfa": [
"build=1.0.118.0",
"proxy=none"
],
"beta": [
"proxy=http"
"build=1.0.20.0"
]
}
I am getting all both the key and value from the json but i only need to extract key: value of (build =).
my desired output is
abc:1.0.44.0
xyz:1.0.127.0 ....etc I tried many options but couldn't get desired results.
jsonurl = http://localhost:8080/test.json
a = urllib2.urlopen(jsonurl).read()
b = json.loads(a)
for x, y in b.iteritems():
print x, y
Prints each key/value in the dictionary. Each of your values is actually a list, so to access a list item, you would need to use the proper syntax.
for x, y in b.iteritems():
print x, y, y[0]
Will show your key, value, and value[0].
Now, identify which element of the list contains the build= string:
> my_list = ["proxy=https", "build=1.0.127.0"]
> build_str = [i for i in my_list if 'build=' in i][0]
> build_str
build=1.0.127.0
From there, you can evolve your program to parse the string. To parse a string as you are asking, I usually look for an easy 'split' delimiter. In this case, the = stands out. Split will take a string and create a list with breaks at every delimiter.
> my_str_as_a_list = "build=1.0.20.0".split('=')
> my_str_as_a_list
['build', '1.0.20.0']
> my_str_as_a_list[1]
1.0.20.0
Now, apply this concept to your for loop:
for key, value in b.iteritems():
my_str = [i for i in value if 'build=' in i][0]
v = my_str.split('=')[1]
print '{}:{}'.format(key, v)
I am not sure if you want an output in the form of a dictionary/string/list based on your question, but you should be able to get there easily with the provided answers.
Try as follows:
data = {
"abc": [
"build=1.0.44.0",
"proxy=none"
],
"xyz": [
"build=1.0.127.0",
"proxy=https"
],
"alfa": [
"build=1.0.118.0",
"proxy=none"
],
"beta": [
"build=1.0.20.0",
"proxy=http"
]
}
res = {}
for k,v in data.items():
res[k] = v[0].split('=')[1] if 'build=' in v[0] else v[1].split('=')[1]
Or using dictionary comprehension:
res = {k: v[0].split('=')[1] if 'build=' in v[0] else v[1].split('=')[1] for k,v in data.items()}
Output:
>>> res
{'xyz': '1.0.127.0', 'abc': '1.0.44.0', 'alfa': '1.0.118.0', 'beta': '1.0.20.0'}
Just iterate and keep the key whose value matches
output_keys = [key for key, value in myjsons if value[0] == 'build=.....']
there is not a fast way to do it without iterating, since dictionaries are intended for lookup on keys, not values

Categories

Resources