Create new List object in python [closed] - python

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 6 months ago.
Improve this question
I am a beginner in python. I want to Create new List object in python.
My Code:
recordList=[]
mappedDictionay={}
sectionGroupName= None
for record in recordCols:
item = record
print item
if not sectionGroupName == record[0]:
sectionGroupName = record[0]
del recordList[0:] # Here I want to create new list object for recordList
recordList.append(item)
mappedDictionay[sectionGroupName] = recordList
else:
recordList.append(tempItem)

It's not that easy to understand your question, especially since your code lost its formatting, but you can create new list objects quite easily. The following assigns a new list object to the variable recordList:
recordList = list()
You could also use
recordList = []
[] and list() are equivalent in this case.

Python is garbage-collected. Just do
recordList = []
and you'll have a new empty list.

Don't use del. Period. It's an "advanced" thing.
from collections import defaultdict
mappedDictionay= defaultdict( list ) # mappedDictionary is a poor name
sectionGroupName= None
for record in recordCols:
mappedDictionay[record[0]].append( record )

You can use list() or simply [] to create a new list.
However, I think what you are trying to achieve can be solved simply by using grouby:
from itertools import groupby
mappedIterator = groupby(recordCols, lambda x: x[0])
or
from itertools import groupby
from operator import itemgetter
mappedIterator = groupby(recordCols, itemgetter(0))
if you prefer.
The groupBy function will return an iterator rather than a dictionary, where each item is of the form (category, sub-iterator-over-items-in-that-category).
If you really want to convert it into a dictionary like you have it in your code, you can run the following afterwards:
mappedDictionary = dict(( (x[0], list(x[1])) for x in mappedIterator ))

You want to create a new list?
It's easy: for eg, you wanna make a list of days, write the following:
new_list=['mon','tue','wed','thurs','fri',sat','sun']
Here the name of the list is new_list and it contains the name of different week days.
Note: never forget use [ ] brackets to make a list, using ( ) will create a tuple, a very different object and { } will create a dictionary object which will raise a error instead.

It's easy to create a new list!
If you want it empty, then just define it like this:
NameOfList = []
or:
NameOfList = list()

Related

How to make a list from a query? [duplicate]

This question already has answers here:
How to modify list entries during for loop?
(10 answers)
Closed 11 months ago.
I run a query and want to make a list from this query. I only need those select items, which I got, but I can't get rid of "," in lst.
I tried replace but it didn't work.
query = """
select
supplier_no_and_name,
accepted,
rejected,
pending,
tdc
from edl_current.supplier_warranty_cost_recovery_warranty_alteryx
where claim_date > "2021-01-01"
"""
lst = query.split()
lst = lst[1-len(lst):len(lst)-13]
for i in range(len(lst)):
lst[i].replace(',',"")
print(lst)
The output is following:
['supplier_no_and_name,', 'accepted,', 'rejected,', 'pending,', 'tdc']
replace method has a return value which is string meaning it doesn't update the original value itself. So, you need to assign with a new value using same variable or anything.
lst[i] = lst[i].replace(',',"")
str.rstrip() and list comprehension would be simpler.
# for i in range(len(lst)):
# lst[i]=lst[i].replace(',',"")
l = [ x.rstrip(',') for x in lst ]
lst = l[:l.index('tdc')+1] # for making same output.
Try this:-
query = """
select
supplier_no_and_name,
accepted,
rejected,
pending,
tdc
from edl_current.supplier_warranty_cost_recovery_warranty_alteryx
where claim_date > "2021-01-01"
"""
lst = query.split()
lst = lst[1-len(lst):len(lst)-13]
for i in range(len(lst)):
lst[i] = lst[i].replace(',', "")
d = ' '.join(lst)
print(d)
Things you should follow next time you ask questions on stack overflow.
Add the expected output in proper format.
Show the things that you've tried in the post.
Frame your question properly and always add error message if found any.
Most importantly search the question on stack overflow before posting it
85 % of time you'll get the answers without posting.
Your current solution is super brittle in that you need to know in advance the exact number of words in your SQL statement. I think you want to try to be a little more flexible and pick out the SELECT and FROM clauses:
query = """
select
supplier_no_and_name,
accepted,
rejected,
pending,
tdc
from edl_current.supplier_warranty_cost_recovery_warranty_alteryx
where claim_date > "2021-01-01"
"""
query_parts = [
p.strip(",")
for p
in query.replace("\n", " ").split()
if p
]
select_index = query_parts.index("select")
from_index = query_parts.index("from")
lst = query_parts[select_index+1 : from_index]
print(lst)
This should give you:
['supplier_no_and_name', 'accepted', 'rejected', 'pending', 'tdc']
Without being sensitive to the number of words or columns.
Since strings are immutable, their replace() method returns a new string with the modifications as opposed to doing them "in place". This means you have to explicitly replace the values in the list.
for i, value in enumerate(lst):
lst[i] = value.replace(',', '')

Create a list with duplicates [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm implementing a procedure in my case "getDuplicatesAlphabetical" that takes a list of person objects and returns a tuple containing all the names that appear multiple times
at this..
This is what I have so far:
def getDuplicatesAlphabetical(listOfPersonObjects):
l = []
dup = []
for person in listOfPersonObjects:
if person not in l:
l.append(person)
else:
dup.append(person)
return sorted(dup)
getDuplicatesAlphabetical(toObjectList(['Thomas', 'Michael', 'Thomas','Susanne','Michael','Thomas','Alfred','Alfred']))
#shall output: ('Alfred', 'Michael', 'Thomas')**
I just do not understand what is missing.. Can somebody help me?
Regards, Mike
This is what a set is for! Checking if an item exists in a set is much cheaper O(1) than checking if it exists in a list O(n). The additional advantage is that adding an element that already exists in the set doesn't actually duplicate it.
def getDuplicatesAlphabetical(listOfPersonObjects):
l = set()
dup = set()
for person in listOfPersonObjects:
if person not in l:
l.add(person)
else:
dup.add(person)
return sorted(list(dup))
Testing this, we get
getDuplicatesAlphabetical(toObjectList(['Thomas', 'Michael', 'Thomas','Susanne','Michael','Thomas','Alfred','Alfred']))
# Output: ['Alfred', 'Michael', 'Thomas']
Another way is to count the instances of all names, and return the ones that have more than one occurrence. You can use the inbuilt collections.Counter for that, or do it yourself.
def getDuplicatesAlphabetical(listOfPersonObjects):
counts = {}
for person in listOfPersonObjects:
countkey = person
counts[countkey] = counts.get(countkey, 0) + 1
return sorted([name for name, count in counts.items() if count > 1])
Remember that dict keys can only be immutable objects, so if listOfPersonObjects has mutable elements, you will have to do something like countkey = person.name or countkey = person['name']
Your code doesn't check to see if the item is already in dup. An easy fix would be to add:
if person in dup:
continue
or change the else to:
elif person not in dup:
dup.append(person)
FWIW a much easier way to count up items (e.g. for finding duplicates) is collections.Counter:
>>> from collections import Counter
>>> def get_dupes_sorted(names):
... return sorted(name for name, count in Counter(names).items() if count > 1)
...
>>> get_dupes_sorted(['Thomas', 'Michael', 'Thomas', 'Susanne', 'Michael', 'Thomas', 'Alfred', 'Alfred'])
['Alfred', 'Michael', 'Thomas']
Using Counter should also be faster for large data sets than using lists because it uses a dictionary internally; checking if an item is in a list requires scanning the entire list (so it gets slower as the list gets bigger, i.e. "linear time"), whereas locating an item in a dictionary or set takes the same amount of time (i.e. "constant time") regardless of how many other items there are.
I'm assuming that a personObject is either an alias for a string or is an object that correctly implements the various comparators that are needed for in and sorted to work -- if not, then that might be an additional problem! But it's impossible to debug that without seeing your implementation of toObjectList.
First remove listOfObject() function. It is not defined yet.
and then change the if statement like the following
if listOfPersonObjects.count(person)>1:
if person in dup:
l.append(person)
else:
dup.append(person)
Output:['Alfred', 'Michael', 'Thomas']

Create many empty dictionary in Python

I'm trying to create many dictionaries in a for loop in Python 2.7. I have a list as follows:
sections = ['main', 'errdict', 'excdict']
I want to access these variables, and create new dictionaries with the variable names. I could only access the list sections and store an empty dictionary in the list but not in the respective variables.
for i in enumerate(sections):
sections[i] = dict()
The point of this question is. I'm going to obtain the list sections from a .ini file, and that variable will vary. And I can create an array of dictionaries, but that doesn't work well will the further function requirements. Hence, my doubt.
Robin Spiess answered your question beautifully.
I just want to add the one-liner way:
section_dict = {sec : {} for sec in sections}
For maintaining the order of insertion, you'll need an OrderedDict:
from collections import OrderedDict
section_dict = OrderedDict((sec, {}) for sec in sections)
To clear dictionaries
If the variables in your list are already dictionaries use:
for var in sections:
var.clear()
Note that here var = {} does not work, see Difference between dict.clear() and assigning {} in Python.
To create new dictionaries
As long as you only have a handful of dicts, the best way is probably the easiest one:
main = {} #same meaning as main = dict() but slightly faster
errdict = {}
excdict = {}
sections = [main,errdict,excdict]
The variables need to be declared first before you can put them in a list.
For more dicts I support #dslack's answer in the comments (all credit to him):
sections = [dict() for _ in range(numberOfDictsYouWant)]
If you want to be able to access the dictionaries by name, the easiest way is to make a dictionary of dictionaries:
sectionsdict = {}
for var in sections:
sectionsdict[var] = {}
You might also be interested in: Using a string variable as a variable name

Pythonic way to hash through dict of dicts dynamically? [duplicate]

This question already has answers here:
Automatically add key to Python dict
(3 answers)
Closed 7 years ago.
Suppose I create a dict like so:
foods = {}
And I eventually want to mutate some value of a nested dict within foods that doesn't yet exist:
foods['fruit']['apples'] = ['Granny Smith']
Is there a nice way to accomplish this insertion without checking the whole way:
if 'fruit' not in foods:
foods['fruit'] = {}
if 'apples' not in foods['fruit']:
foods['fruit']['apples'] = []
foods['fruit']['apples'].append('Granny Smith')
I guess I'm looking for a way to dynamically hash into nested dicts without explicitly instantiating them along the way.
I love the Python standard library. You want to use collections.defaultdict.
In this case, you want to nest them, so that foods is a defaultdict that, on the requested item not existing, generates a defaultdict that, on the requested item not existing, generates a list. Sounds complicated, but in the end, the result is not:
>>> from collections import defaultdict
>>> foods = defaultdict(lambda: defaultdict(list))
>>> foods['fruit']['apples'].append('Granny Smith')
>>> print(foods['fruit']['apples'])
['Granny Smith']
Your code:
if 'fruit' not in foods:
foods['fruit'] = {}
if 'apples' not in foods['fruit']:
foods['fruit']['apples'] = []
foods['fruit']['apples'].append('Granny Smith')
would be written as:
foods.setdefault('fruit', {}).setdefault('apples', []).append('Granny Smith')
Using setdefault(key[, default]).

Make this code look more elegant [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I am absolutly new in python and in programing, I made this bifid cipher, I'd like to hear opinions about how to improve and make it look more elegant, thanks in advance.
I been taking courses in Codecademy and Udacity, and I've learn quite a lot.
import itertools
#Genera coodernadas-Generate Coordinates
coordinates = [[x,y] for x in range(1,6) for y in range(1,6)]
#Genera alfabeto-Generate Alphabet
alfa = []
for i in range(97,123):
alfa.append(chr (i))
alfa.remove("i")
#Genera diccionario de coordenadas y alfabeto - Generate dictionary and coordinates alphabet
alfacor = {}
alfacor = dict(zip(alfa,coordinates))
#Leer Txt - Read txt
document = open("Z:\\R\\Desktop\\BIFIDO\\easy.txt")
contenido = document.read()
print (contenido)
document.close()
#Encripta fase1 - Get's coordinates of txt
encripta = []
for e in contenido:
encripta.append(alfacor[e])
#Unir lista encripta - Merge content of encropita in a new list
merged = list(itertools.chain.from_iterable(encripta))
#Divido lista merge en partes iguales - Divide meged list to get new coordinates
B = merged[:len(merged)/2]
C = merged[len(merged)/2:]
#Unir B y C - Zip B and C to get a new list of coordinates
zipped = zip(B,C)
#Make a new list from zipped to convert from tuple to list
final_list = [list(elem) for elem in zipped]
#Convert contect of alfacor to tuples
inv_alfacor = {}
for letter, coordinate in alfacor.iteritems():
inv_alfacor[tuple(coordinate)] = letter
#Substitude coordinates of final_list from elements of inv_alfacor
encripta_f = []
for element in final_list:
element = tuple(element)
if element in inv_alfacor:
encripta_f.append(inv_alfacor[element])
print "Tu palabra ",encripta_f
Other than perhaps using comprehensions and avoid the unnecessary tuple -> list -> tuple conversions, reduce the number of intermediate variables then it might be slightly easier to read. I would also consider making it a function that you pass in a string and an encrypted string is returned:
from itertools import chain, product
def bifid(data):
# Leave coordinates as tuples and appropriate use of itertools.product
coordinates = product(range(1, 6), repeat=2)
# Using comprehensions and generators to construct the list/dicts vs loops
# Leave alfa as a generator as it is only used once
alfa = (chr(i) for i in range(97, 123) if chr(i) != 'i')
alfacor = dict(zip(alfa, coordinates))
inv_alfacor = {coordinate: letter for letter, coordinate in alfacor.iteritems()}
encripta = (alfacor[e] for e in data)
merged = list(chain(*encripta))
final_list = zip(merged[:len(merged)//2], merged[len(merged)//2:])
return "".join(inv_alfacor[e] for e in final_list if e in inv_alfacor)
# Use with it closes automatically and handles exceptions correctly
with open("Z:\\R\\Desktop\\BIFIDO\\easy.txt") as document:
data = document.read()]
print "Tu palabra: {}".format(bifid(data))
Output:
"helloworld" -> Tu palabra: kmcyobnalt
Use with statement
You can read more in python docs or in this article Understanding Python's "with" statement
Suggested modification:
#Leer Txt - Read txt
with open("Z:\\R\\Desktop\\BIFIDO\\easy.txt", "r") as document:
contenido = document.read()
print (contenido)
Use list comprehensions
More info in Python docs or in the tutorial Python Tutorial: List Comprehensions
Suggested modification:
#Genera alfabeto-Generate Alphabet
alfa = [chr(i) for i in xrange(97, 123) if chr(i) != "i"]
(Note, please, this change also includes a condition in the list comprehension - example at SO question)
And also:
#Encripta fase1 - Get's coordinates of txt
encripta = [alfacor[e] for e in contenido]
Use generators
The first thing you can start with is following. When you write a list comprehension and you know you are going to iterate only one item of the list a time, change the brackets from [] to (). This is really simplified but it is the first thing you can do. Another related tip, when you use range(x) just like for i in range(x), use xrange(x) instead. xrange is a generator version of range.
More info in Python Wiki
Suggested change:
#Make a new list from zipped to convert from tuple to list
final_list = (list(elem) for elem in zipped)
Printing
In this case, using the print you used is fine, but have a look at string formatting.
More in Python docs and a few examples here.
Possible change:
print "Tu palabra {}".format(encripta_f)
You don't need to initialize all the variables.
You don't need to initialize alfacor dictionary when you assign a completely new value to the variable. However, you need to initialize variable when you work with it later.
Thus there is a difference between
# no need for initialization
alfacor = {}
# because you assign a new value here to the variable `alfacor`
alfacor = dict(zip(alfa,coordinates))
and this:
# you need to initialize this
alfacor = {}
# because you are working with the empty dictionary here
alfacor["my_key"] = "my_value"

Categories