Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I want to add an element to a list, but the list might not exist yet. In which case, I'd create a list of that single element. It might be an entry in a dictionary. It's my responsibility to add to a particular field - hence the append. But, if it's the first time I'm doing it, the key doesn't even exist in the dictionary yet. Hence the set to a list of a single element.
So in a nutshell, the following
if 'dependencies' in userdata:
userdata['dependencies'].append('foo')
else:
userdata['dependencies'] = ['foo']
This feels very unpythonic and ugly. What are some better options?
use try...except like below:
try:
X.append('foo')
except NameError:
print("you need create list first. I create list for you. then append.")
X = ['foo']
EDIT : base on your editing question:
from collections import defaultdict
userdata = defaultdict(list)
userdata['dependencies'].append('foo')
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
a = [5,2,7]
If 2 is the latest element added in a then return 2 .
You can use this syntax:
>>> list_ = [0, 1, 2]
>>> list_[-1]
2
There is no direct way of knowing how a list was modified. Python does not keep track of this information. This means you would have to keep a copy of the list before updating it and run something like
a = [5,2,7]
old_a = a.copy()
a[1] = 0
[old_a[i] for i,v in enumerate(a) if old_a[i]!=v]
However, if you are able to keep track of this, you are certainly able to keep track of the added value, and to run the tests before adding it to the new list. In summary, the design of what you are doing should probably be reconsidered.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
So in my niche use case I want to create a hash map in python to store a large list dataset. This list has a key value as a tuple (i.e (1,2)) and my goal is to search the list and see if the tuple exists.
I know this is achievable with a regular list but I wanted the time complexity of O(1) with the hash map functionality. But when adding elements to the dictionary, I am doing this:
dictionary[(1,2)] = None
Because I couldn't care less about the value associated with the key.
Is this good coding practice or is there something else I should use?
If you don't give a toss about the value, you can use a set. From the python source code (line 4 of Objects/setobject.c):
Derived from Lib/sets.py and Objects/dictobject.c.
If you need to iterate over a set, you should use a list or do the conversion as needed.
I would suggest using defaultdict. By default, any values not in the dictionary would be False.
from collections import defaultdict
lookup = defaultdict(bool)
lookup[(1,2)] = True
Examples:
l = [(1,2), (3,4), (5,6)]
for e in l:
lookup[e] = True
print(lookup[(3,4)])
# True
print(lookup[(8, 9)])
# False
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a file from which I have to do some training from data.
This file contains some words.
I'd like to create a list which contains another list. The second list, is made of a key-value pair.
For example:
The word Will can be either a name or a modal.
My list should be something like that:
Will --> 1.[Key]Noun : [Value] some-number --> 2. [Key]Modal: [Value] some-other-number
How can I implement this in Python?
I believe that in Java this could be implemented using an Hashmap which contains another hashmap if i'm not mistaken.
I think you are thinking of dictionaries, not lists. Lists in python are akin to arrays, Dictionaries are as you guess similar to hashmaps, and can only have unique keys, but can hold other dictionaries. You can also have a list of dictionaries, or a dictionary of lists.
For your project I'm just guessing you want something like.
words={"Will":{"Noun":1,"Modal":2}}
which you would then access by doing
>>> print(words)
{'Will': {'Noun': 1, 'Modal': 2}}
>>> print(words["Will"])
{'Noun': 1, 'Modal': 2}
>>> print(words["Will"]["Noun"])
1
>>> print(words["Will"]["Modal"])
2
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a list of data with 10 elements called DATA.
Each element is a dictionary (DATA[0] is a dictionary, DATA[1] is a dictionary, .. DATA[9] is a dictionary).
Each of these dictionaries has a key called "Date".
Is there any way I can extract the individual values corresponding from the 'Date' key from each of these 10 dictionaries into their own separate list?
In the end, my list would be NEWLIST = {DATA[0]['Date'], DATA[1]['Date'], .... , DATA[9]['Date']).
Is there any way to do this without a for loop?
you can try list comprehension:
NEWLIST = [x["date"] for x in DATA]
This should be a straightforward list comprehension.
If you're not familiar with that construct, I recommend that you find and work through a tutorial on the topic.
Instead of stepping explicitly through the list, just iterate over the list.
new_list = [data_dict['Date'] for data_dict in DATA]
Note that I've changed all but the original list name to conform to PEP8 guidelines.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
The syntax for checking if an item is already in a list and then adding it to a list if it is not is:
foo = []
if item not in foo:
foo.append(item)
# do something
This can execute code on the condition that the item is not in foo. This syntax seems to duplicate the logic of a set datatype in python, yet the following syntax does not exist;
bar = set()
if not bar.add(item):
# do something
but add() returns nothing, so this is not possible. So how does one execute some logic conditionally on an item being in a set?
Note: the reason a set is desired is the operation of adding a unique value to a set is of O(1), whereas the same operation is O(n) on a list.
Just remove the if.
bar = set()
bar.add(item):
# do something
Note that you have foo.append(item) when using a list. The only thing that changes is the function name when you use a set.