my_text1 = 'text1'
my_text2 = 'text2'
my_list = []
my_dict = {}
my_dict['Key1'] = my_text1
my_dict['Key2'] = my_text2
my_list.append(my_dict)
What's the fastest way to create a list of dictionaries?
Is it possible to use write variable in dictionary?
I wanted to make something like this:
my_list.append('key1'= %s, 'key2'= %s % (my_text1, my_text2))
I know it's wrong syntax but It's my goal to append different values from variables
Use the dictionary literal syntax, {...}
my_list.append({"key1": my_text1, "key2": my_text2})
I'll take it a step further and assume you have a list of texts you want to format as dicts and append to a list:
[{"key%d" % (i + 1) : text for i, text in enumerate(text_list)} for text_list in list_of_lists]
There is this other syntax you can try:
my_list.append(dict(key1=my_text1, key2=my_text2))
Not sure about this issue of "fastest" considering the fact that doing something like this is quite simple in python. The above syntax is probably fastest to write, but I have a feeling that's not what you are after.
The fastest way is to be declarative:
my_list = [{'Key1': 'text1', 'Key2': 'text2'}]
Related
I get how to do regular comprehension style conversions for For loops, but this, I can't wrap my head around.
I know that normally you would change the lines 3-5 into one line, but is it possible to include the empty list in the comprehension?
The code is
text = input().lower()
dict = {}
for x in text:
if x.isalpha()
dict[x] = text.count(x)
print(dict)
I don't even know where to get started.
Don't use dict as a variable name, it's the name of a built-in function.
To convert the loop to a dictionary comprehension, change dict[key] = value to key: value, then follow it with the for loop and if condition.
text_dict = {x: text.count(x) for x in text if x.isalpha}
Note that Python has a standard library function collections.Counter() that does this.
from collections import Counter
text_dict = Counter(filter(str.isapha, text))
By referring to the dictionary comprehension posted by #Barmar, another way to do so is using dictionary comprehension and set:
result = dict((x,text.count(x)) for x in set(text.lower()) if x.isalpha)
I successfully imported from the web this json file, which looks like:
[{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"},
etc ...
I want to extract the values of the key moid_au, later compare moid_au with the key values of h_mag.
This works: print(data[1]['moid_au']), but if I try to ask all the elements of the list it won't, I tried: print(data[:]['moid_au']).
I tried iterators and a lambda function but still has not work yet, mostly because I'm new in data manipulation. It works when I have one dictionary, not with a list of dictionaries.
Thanks in advance for other tips. Some links were confusing.
Sounds like you are using lambda wrong because you need map as well:
c = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"},{"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}]
list(map(lambda rec: rec.get('moid_au'), c))
['0.035', '0.028']
Each lambda grabs a record from your list and you map your function to that.
Using print(data[:]['moid_au']) equals to print(data['moid_au']), and you can see that it won't work, as data has no key named 'moid_au'.
Try working with a loop:
for item in data:
print(item['moid_au'])
using your approach to iterate over the whole array to get all the instances of a key,this method might work for you
a = [data[i]['moid_au']for i in range(len(data))]
print(a)
In which exact way do you want to compare them?
Would it be useful getting the values in a way like this?
list_of_dicts = [{"h_mag":"19.7","i_deg":"9.65","moid_au":"0.035"}, {"h_mag":"20.5","i_deg":"14.52","moid_au":"0.028"}]
mod_au_values = [d["moid_au"] for d in list_of_dicts]
h_mag_values = [d["h_mag"] for d in list_of_dicts]
for key, value in my_list.items ():
print key
print value
for value in my_list.values ():
print value
for key in my_list.keys():
print key
I'm using python 3.x and I want to create a dictionary from a list. That is, I have each key and value concatenated in a string, and each entry as an element in a list.
my_list = ['val1 key1', 'val2 key2', 'val2 key2']
I can split it into two lists using
values,keys = zip(*(s.split() for s in my_list))
Creating a dictionary from there is easy. Since I still need to do stuff to the keys and values, I do:
my_dict = {k[:-1]:float(v) for k,v in zip(keys,values)}
Out of mere curiosity, I was wondering If there is a way where to avoid the intermediate lists. In short I need to access each list element, split the string, do something to each split part and input it as key:value pair into a dictionary. Following this question I tried
my_dict = {k[:-1]:float(v) for v,k in zip(*(s.split() for s in my_list))}
But I get ValueError: too many values to unpack (expected 2). Then I tried simply using a generator (I think it's a generator) inside the dictionary comprehension syntax and it work. But I don't like it, since the second for is used only to extract an element from the list:
my_dict = {s[1][:-1]:float(s[0]) for s in (s.split(', ') for s in my_list)}
This is what I'm currently using and works perfectly, but I'd like to know why the second solution doesn't work. to me, it seems it should, and that my solution uses one to many for. I'm aware it's not a super relevant question, but I'd like to learn. Also, I'm open to title suggestions.
EDIT1: Fixed a few syntax errors I had.
EDIT2: A full working and explicit example with expected result, as suggested. I'm still working on making good mcve's:
my_list = ['1.123, name1\n', '2.3234, name2\n', '3.983, name3\n', '4.23, name4\n']
The output I want is what I would get if I manually did
my_dict = {'name1':1.123, 'name2':2.3234, 'name3':3.983, 'name4':4.23}
Method that creates intermediate lists:
values,keys = zip(*(s.split(', ') for s in my_list))
print(values)
>>> ('1.123', '2.3234', '3.983', '4.23')
print(keys)
>>> ('name1\n', 'name2\n', 'name3\n', 'name4\n')
my_dict = {k[:-1]:float(v) for k,v in zip(keys,values)}
print(my_dict)
>>> {'name4': 4.23, 'name2': 2.3234, 'name1': 1.123, 'name3': 3.983}
Example that I don't know why it does not work:
my_dict = {k[:-1]:float(v) for v,k in zip(*(s.split(', ') for s in my_list))}
>>> ValueError: too many values to unpack (expected 2)
Working example that to me, seems it uses one to for inside the list/dict comprehension/generator expression:
my_dict = {s[1][:-1]:float(s[0]) for s in (s.split(', ') for s in my_list)}
print(my_dict)
>>> {'name4': 4.23, 'name2': 2.3234, 'name1': 1.123, 'name3': 3.983}
My actual strings look something like '0.9493432915614861, zf_AB012_bn_BOS\n'
, that's why I use a more readable example.
EDIT3: I just learned of the str.strip() method. This makes the line creating the dictionary a bit nicer:
my_dict = {s[1].strip():float(s[0]) for s in (s.split(', ') for s in my_list)}
def dict_unzip(lst):
for x in lst:
yield reversed(x.split(' ', 1))
my_dict = dict(dict_unzip(my_list))
But since it's Python3 things are notably simpler actually:
my_dict = dict(map(lambda s: reversed(s.split(' ', 1)), my_list))
Or even
my_dict = dict(reversed(s.split(' ', 1)) for s in my_list)
Using Python 2.7.9: I have a list of dictionaries that hold a 'data' item, how do I access each item into a list so I may get the mean and standard deviation? Here's an example:
values = [{'colour': 'b.-', 'data': 12.3}, {'colour': 'b.-', 'data': 11.2}, {'colour': 'b.-', 'data': 9.21}]
So far I have:
val = []
for each in values:
val.append(each.items()[1][1])
print np.mean(val) # gives 10.903
print np.std(val) # gives 1.278
Crude and not very Pythonic(?)
Using list comprehension is probably easiest. You can extract the numbers like this:
numbers = [x['data'] for x in values]
Then you just call numpys mean/std/etc functions on that, just like you're doing.
Apologies for (perhaps) an unnecessary question, I've seen this:
average list of dictionaries in python
vals = [i['data'] for i in values]
np.mean(vals) # gives 10.903
np.std(vals) # gives 1.278
(Pythonic solution?)
It is an exceptionally bad idea to index into a dictionary since it has no guarantee of order. Sometimes the 'data' element could be first, sometimes it could be second. There is no way to know without checking.
When using a dictionary, you should almost always access elements by using the key. In dictionary notation, this is { key:value, ... } where each key is "unique". I can't remember the exact definition of "unique" for a python dictionary key, but it believe it is the (type, hash) pair of your object or literal.
Keeping this in mind, we have the more pythonic:
val = []
for data_dict in values:
val.append(data_dict['data'])
If you want to be fancy, you can use a list completion which is a fancy way of generating a list from a more complex statement.
val = [data_dict['data'] for data_dict in values]
To be even more fancy, you can add a few conditionals so check for errors.
val = [data_dict['data'] for data_dict in values if (data_dict and 'data' in data_dict)]
What this most-fancy way of doing thing is doing is filtering the results of the for data_dict in values iteration with if (data_dict and 'data' in data_dict) so that the only data_dict instances you use in data_dict['data'] are the ones that pass the if-check.
You want a pythonic one Liner?
data = [k['data'] for k in values]
print("Mean:\t"+ str(np.mean(data)) + "\nstd :\t" + str(np.std(data)))
you could use the one liner
print("Mean:\t"+ str(np.mean([k['data'] for k in values])) + "\nstd :\t" + str(np.std([k['data'] for k in values])))
but there really is no point, as both print
Mean: 10.9033333333
std : 1.27881021092
and the former is more readable.
Can I append to a list in a dictionary?
test = {'food' : 'apple'}
Is there a command to add 'banana' and turn it into
test = { 'food': ['apple','banana'] }
Thank you
No, since it isn't a list in the first place.
test['food'] = [test['food'], 'banana']
You need to create a dict where the values are lists:
test = {'food' : ['apple']}
test['food'].append('banana')
The simplest solution would just be to just make the value of your hash a list, that may contain just one element. Then for example, you might have something like this:
test = {'food' : ['apple']}
test['food'].append('banana')
I'd recommend using a defaultdict in this case, it's pretty straightforward to deal with dictionaries of lists, since then you don't need two separate cases every time you modify an entry:
import collections
test = collections.defaultdict(list)
test['food'].append('apple')
test['food'].append('banana')
print test
# defaultdict(<type 'list'>, {'food': ['apple', 'banana']})