I'm just starting out at Python and need some help with dictionaries. I'm looking to add keys to a dictionary based on input that is a list with string elements:
Ex.
x = {}
a = ['1', 'line', '56_09', '..xxx..']
Now say a while loop has come to this list a. I try to add to the dictionary with this code:
if a[1] == 'line':
x[a[2]] = [a[-1]]
I want the dictionary to read x = { '56_09': '..xxx..'} and want to confirm that by printing it. Do i need to adjust the elements on the list to strings or is it something with the if statement that I need to change?
The one problem with your code is in the if block:
if a[1] == 'line':
x[a[2]] = [a[-1]]
Instead, it should be like this:
if a[1] == 'line':
x[a[2]] = a[-1]
What you did was creating a list with one element: the last element of the list a.
you can make a dict object form two lists using ZIP and dict()
dict(zip(list1,list2)).
I believe for your question make two list form the input list based on the requirement and use above syntax.
I think you need something like this : -
def check(x,a):
if 'line' in a[1]:
x[a[2]] = a[-1]
return x
After
check({},['1', 'line', '56_09', '..xxx..'])
if a[1]=='line':
x={a[2]:a[-1]}
dictionary comprehension Create a dictionary with list comprehension in Python
{r:"test" for r in range(10)}
Related
My list of lists looks like this:
my_list = [[sub_list_1],[sub_list_2],...,[sub_list_n]]
Desired output
my_dict[1] = [sub_list_1]
my_dict[2] = [sub_list_2]
my_dict[n] = [sub_list_n]
I want the keys for the dictionary to be generated on their own. How can this be achieved in a pythonic way?
I look at certain questions like
Converting list of lists in dictionary python
Python: List of lists to dictionary
Converting nested lists to dictionary
but they either provide a list of keys or focus on using some information from the lists as keys.
Alternatively, I tried making a list of keys this way:
my_keys = list(range(len(my_list)))
my_dict = dict(zip(my_keys,my_list)
and it works but, this does not:
my_dict = dict(zip(list(range(len(my_list))),my_list))
This gives me a syntax error.
So in summary:
Is there a way to generate a dictionary of lists without explicitly providing keys?, and
Why does the combined code throw a syntax error whereas the two step code works?
I would recommend to use a dict comprehension to achieve what you want like in here, moreover I tried your implementation and haven't faced any issues (more details are more than welcome):
my_list = [["sub_list_1"],["sub_list_2"],["sub_list_3"]]
my_dict = dict(zip(list(range(len(my_list))),my_list))
alternative_dict = {iter:item for iter,item in enumerate(my_list)}
print("yours : " + str(my_dict))
print("mine : " + str(alternative_dict))
output:
yours : {0: ['sub_list_1'], 1: ['sub_list_2'], 2: ['sub_list_3']}
mine : {0: ['sub_list_1'], 1: ['sub_list_2'], 2: ['sub_list_3']}
Your syntax error is caused by your variable name try. try is allready a name in python. see try/except
This should do it
my_dict = {my_list.index(i) + 1: i for i in my_list}
Notice that I have added +1 to start at the key 1 instead of 0 to match your expectations
I received no error message when running your code:
>>> my_list = [["hello1"], ["hello2"]]
>>> my_dict = dict(zip(list(range(len(my_list))), my_list))
>>> my_dict
{1: ['hello1'], 2: ['hello2']}
You can create a dict of lists from a list of lists using a dict comprehension:
my_dict = {i: sub_list for i, sub_list in enumerate(my_list)}
This may seem odd, but I am trying to remove a part of an item contained in a list. Basically, I am trying to remove a specific character from multiple list elements. For example
list = ['c1','c2','c3','d1','s1']
list.remove('c')
I know that doing that wouldn't work, but is there any way to remove the "c"s in the list, and only the "c"s in Python 3?
lst = [s.replace('c','') for s in lst]
# ['1','2','3','d1','s1']
List comprehensions are your friend. Also note the "list" is a keyword in Python, so I highly recommend you do not use it as a variable name.
Use list comprehensions,
list = ['c1','c2','c3','d1','s1']
list_ = [ x for x in list if "c" not in x ] # removes elements which has "c"
print list_ # ['d1', 's1']
list1 = ['c1','c2','c3','d1','d2']
list2 = []
for i in range (len(list1)):
if 'c' not in list1[i]:
list2.append(list1[i])
print (list2) #['d1', 'd2']
and also this link may helpful
Link one
I have list of dictionaries-
[{"id":1,"name":"abc"},{"id":2,"name":"def"},{"id":3,"name":"xyz"}]
I want to get the dictionary where id = 1 and store it in a variable.Something like-
element = {"id":1,"name":"abc"}
I don't want to use for loop to iterate through the list and then fetch the element.
No matter what you do, you'll have to iterate over that list.
g = (e for e in elements if e.get('id') == 1)
element = next(g)
The nice thing about this implementation is it only iterates as much as needed to find the next matching element.
The problem you are addressing is called indexing. If you don't know anything about your matching criterias a priori then there is nothing you can do and you have to do the loop. The easiest implementation would be:
my_obj = next(obj for obj in my_list if my_criterium(obj))
where in your case
my_criterium = lambda obj: obj['id'] == 1
However if you know that you will always search by id then you can create an index:
my_index = {obj['id']: obj for obj in my_list}
Then the retrieveing is as simple as
my_obj = my_index[1]
which no longer requires a loop (and thus is fast).
This is under assumption that id is unique on each object (this assumption is not crutial, you can create a different index by storing a list of matched element for each id). The other drawback is that it will be hard to keep both the index and the list consistent between each other.
But no matter what path you chose there is no escape from a loop.
Dicts = [{"id":1,"name":"abc"},{"id":2,"name":"def"},{"id":3,"name":"xyz"}]
for d in Dicts:
if d.get('id') == 1:
element = d
print element
You can store the ids of your dictionary-list into another dictionary using just one for loop. This will be much faster when you have multiple queries.
In [1]: d = [{"id":1,"name":"abc"},{"id":2,"name":"def"},{"id":3,"name":"xyz"}]
In [2]: indices = {v["id"] : index for index, v in enumerate(d)}
In [3]: element = d[indices[1]]
In [4]: print(element)
{'id': 1, 'name': 'abc'}
In [5]: element = d[indices[3]]
In [6]: print(element)
{'id': 3, 'name': 'xyz'}
I think I have a solution.
Basically, you convert the list into a string and then you play with it to make a single dictionary.
Although, I think that looping over the list is way better.
l = [{"id":1,"name":"abc"},{"id":2,"name":"def"},{"id":3,"name":"xyz"}]
#convert to string
a = str(l)
#remove parenthesis and curly brackets
a = a.replace('{','').replace('}','').replace('[','').replace(']','').replace(' ','')
#remove 'id' and 'name'
a = a.replace("'id':",'').replace(",'name'",'')
#add curly brackets
a = '{'+a+'}'
#make a dict
exec('a='+a)
>>>a
{1: 'abc', 2: 'def', 3: 'xyz'}
As you can see, you end up with a single dictionary with the right key/value pairs without using a single for loop!
I have a dictionary similar to this
x ={'1': [['a','b'],['ac','d']], '2' : [['p','qa'],['r','s']]}
And I would like to access the individual strings i.e. a,b etc , compare if it has "a" in it, delete those.
The main question is - how do I access the strings? How do I change it?
I tried using nested loops, but was unable to change, as I guess assignment stmts do not work that way.
Any idea how to proceed with such situation?
Edit : The naive approach I used -
for item in x:
for ele in x[item]:
for i in ele:
i = #assign new value here using regex comparison
But when I try to print x after this, it stays same.
Obviously. assignment statements do not work this way. Any idea about how should I access the elements to change it?
>>> x ={'1': [['a','b'],['ac','d']], '2' : [['p','qa'],['r','s']]}
>>> for key in x:
... for n, item in enumerate(x[key]):
... x[key][n] = list(filter(lambda l: 'a' not in l, x[key][n]))
...
>>> x
{'2': [['p'], ['r', 's']], '1': [['b'], ['d']]}
In your example,
for item in x:
for ele in x[item]:
for i in ele:
i = #assign new value here using regex comparison
i is a copy of the string in ele, so assigning to it has no effect on the original. You need to modify the list ele. Possibly, ele[ele.index(i)] = #whatever. Note, however, that this will not work correctly if you have identical values in the list. It will only change the first one.
Not sure what you're actually trying to do, but it may be easier to use a list comprehension, at least for the innermost list. This will allow you to change each element of the innermost list. Perhaps,
for item in x.values():
for ele in item:
ele[:] = [#whatever for i in ele]
where ele[:] is needed to change the original inner list (just ele won't work), and I used the more Pythonic x.values() when we actually wanted the values, not the keys.
This is an incredibly simple question (I'm new to Python).
I basically want a data structure like a PHP array -- i.e., I want to initialise it and then just add values into it.
As far as I can tell, this is not possible with Python, so I've got the maximum value I might want to use as an index, but I can't figure out how to create an empty list of a specified length.
Also, is a list the right data structure to use to model what feels like it should just be an array? I tried to use an array, but it seemed unhappy with storing strings.
Edit: Sorry, I didn't explain very clearly what I was looking for. When I add items into the list, I do not want to put them in in sequence, but rather I want to insert them into specified slots in the list.
I.e., I want to be able to do this:
list = []
for row in rows:
c = list_of_categories.index(row["id"])
print c
list[c] = row["name"]
Depending on how you are going to use the list, it may be that you actually want a dictionary. This will work:
d = {}
for row in rows:
c = list_of_categories.index(row["id"])
print c
d[c] = row["name"]
... or more compactly:
d = dict((list_of_categories.index(row['id']), row['name']) for row in rows)
print d
PHP arrays are much more like Python dicts than they are like Python lists. For example, they can have strings for keys.
And confusingly, Python has an array module, which is described as "efficient arrays of numeric values", which is definitely not what you want.
If the number of items you want is known in advance, and you want to access them using integer, 0-based, consecutive indices, you might try this:
n = 3
array = n * [None]
print array
array[2] = 11
array[1] = 47
array[0] = 42
print array
This prints:
[None, None, None]
[42, 47, 11]
Use the list constructor, and append your items, like this:
l = list ()
l.append ("foo")
l.append (3)
print (l)
gives me ['foo', 3], which should be what you want. See the documentation on list and the sequence type documentation.
EDIT Updated
For inserting, use insert, like this:
l = list ()
l.append ("foo")
l.append (3)
l.insert (1, "new")
print (l)
which prints ['foo', 'new', 3]
http://diveintopython3.ep.io/native-datatypes.html#lists
You don't need to create empty lists with a specified length. You just add to them and query about their current length if needed.
What you can't do without preparing to catch an exception is to use a non existent index. Which is probably what you are used to in PHP.
You can use this syntax to create a list with n elements:
lst = [0] * n
But be careful! The list will contain n copies of this object. If this object is mutable and you change one element, then all copies will be changed! In this case you should use:
lst = [some_object() for i in xrange(n)]
Then you can access these elements:
for i in xrange(n):
lst[i] += 1
A Python list is comparable to a vector in other languages. It is a resizable array, not a linked list.
Sounds like what you need might be a dictionary rather than an array if you want to insert into specified indices.
dict = {'a': 1, 'b': 2, 'c': 3}
dict['a']
1
I agree with ned that you probably need a dictionary for what you're trying to do. But here's a way to get a list of those lists of categories you can do this:
lst = [list_of_categories.index(row["id"]) for row in rows]
use a dictionary, because what you're really asking for is a structure you can access by arbitrary keys
list = {}
for row in rows:
c = list_of_categories.index(row["id"])
print c
list[c] = row["name"]
Then you can iterate through the known contents with:
for x in list.values():
print x
Or check if something exists in the "list":
if 3 in list:
print "it's there"
I'm not sure if I understood what you mean or want to do, but it seems that you want a list which
is dictonary-like where the index is the key. Even if I think, the usage of a dictonary would be a better
choice, here's my answer: Got a problem - make an object:
class MyList(UserList.UserList):
NO_ITEM = 'noitem'
def insertAt(self, item, index):
length = len(self)
if index < length:
self[index] = item
elif index == length:
self.append(item)
else:
for i in range(0, index-length):
self.append(self.NO_ITEM)
self.append(item)
Maybe some errors in the python syntax (didn't check), but in principle it should work.
Of course the else case works also for the elif, but I thought, it might be a little harder
to read this way.