Understanding Python Lists and Dictionaries using the example - python

Using this following example:
For each human in the world I would like to create my own list which I can iterate over..
persons = []
attributes = {}
for human in world:
attributes['name'] = human['name']
attributes['eye_color'] = human['eyes']
persons.append(attributes)
Now when I try to print out each name in my own list:
for item in persons:
print item['name']
They are all the same, why?

You are reusing the same dictionary over and over again. persons.append(attributes) adds a reference to that dictionary to the list, it does not create a copy.
Create a new dictionary in your loop:
persons = []
for human in world:
attributes = {}
attributes['name'] = human['name']
attributes['eye_color'] = human['eyes']
persons.append(attributes)
Alternatively, use dict.copy() to create a shallow copy of the dictionary.

Related

Edit list element in multilist - Python

I am using python 3.x, I have the following problem, using the keyboard the user enters certain data and fills N lists to create a contact list, then in a list I collect all the data of the lists, I need to modify the data of each list, (I already have it, I modify the data of a list with a specific value using a for) Example, Names list, I modify Andrew's name, but in the Contacts list, there is all Andrew's information (phone, mail, etc), but I just need to modify in the Contacts list, the value of Andrew
I have all this list:
names = []
surnames = []
phones = []
emails = []
addresses = []
ages = []
salaries = []
genres = []
contacts = []
# and use the append to add the data into the contacts list
contacts.append ([names, surnames, phone numbers, emails, addresses, ages, salaries, genders])
Then I update the info of one contact
search = input(Fore.LIGHTBLUE_EX + "Type the name of the contact you want update: ")
for i in range(len(names)):
if (names[i] == search):
try:
names[i] = input(Fore.MAGENTA + "Type the New name: ")
names[i] = nombres[i].replace(" ", "")
if names[i].isalpha() == True:
print(Fore.GREEN + "Already saved, congrats.")
pause= input(Fore.LIGHTGREEN_EX + "Press enter to exit")
But I dont know how to update the name in the List of contacts.
When you call contacts.append(), you add a list of lists to a list, so your contacts list will look something like this:
contacts = [[[names[0], names[1], ...], [...], [...]]]
It's unnecessary to have a list of one item nested in another list, so I would just call contacts.append() and pass each list (names, surnames, etc.) to the method, which allows for easier indexing.
Since the list names would be the first item in the list contacts (contacts[0]), you could do one of two things (there may be more, but these are off the top of my head):
Reassign the specific index to a new value, using nested-list indexing (contacts[0][0] = "updated name" would update the first item of the names list to "update name")
Reassign the entire nested list to a new list (contacts[0] = new_name_list would reassign contacts[0], formerly the names list, to new_name_list)
On a side note: In this case, I would recommend dictionaries over lists, as it will be easier to keep track of what is being reassigned/modified.
contacts = {
"names": names,
"surnames": surnames,
...
}
Doing this will make it more clear which list your are referring to; contacts[0] doesn't give much information, but contacts["names"] informs readers that you are referring to the names list. This is solely for cleaner code; there isn't much difference in functionality.

A list of structure with Python

I am new in python,
I want work with structured lists:
class X_ItemSet: # Structure of an Item
Item = []
ItemTID = []
oneItem = X_ItemSet #one instance of X_ItemSet
ListTID = [X_ItemSet] #Liste of X_ItemSet
oneItem.Item.append(1)
oneItem.ItemTID.append("a")
ListTID.append(oneItem)
del oneItem[:]
my problem is when deleting oneItem also ListTID will be empty
what should i do to keep values in ListTID when deleting oneItem?

Create variable number of dictionary with name taken from list in Python

I have a list which grows and shrinks in a for loop. The list looks like following :- . With every element inside list of list i want to associate it to a separate dictionary.
list123 = [[1010,0101],[0111,1000]]
In this case I want to create 4 dictionary with the following name
dict1010 = {}
dict0101 = {}
dict0111 = {}
dict1000 = {}
I tried following loop
for list1 in list123:
for element in list1:
dict + str(element) = dict()
This is the error i am getting
SyntaxError: can't assign to literal
while you can dynamically create variables, unless there is an overwhelming need to do that use instead a dictionary of dictionary witch key is the name you want, like this
my_dicts=dict()
for list1 in list123:
for element in list1:
my_dicts["dict" + str(element)] = dict()
and to access one of them do for example my_dicts["dict1010"]
You can uses globals() function to add names to global namespace like this
for list1 in list123:
for element in list1:
globals()["dict"+str(element)] = {}
this will add variables with the names you want as if you created them using dictx={} also numbers that begins with 0 won't convert well using str() so you should make your list a list of strings
First of all, I must say that you shouldn't do this. However, if you really want to, you can use exec.
If you really want to do this, you could use exec:
list123 = [[1010,0101],[0111,1000]]
for list1 in list123:
for element in list1:
var = 'dict' + str(element)
exec(var + ' = dict()')

Append multiple items into list of lists in Python

I am trying to append items into lists of list but instead i am getting an equivalent of extend().
doc = __doc__
result = []
collector = FilteredWorksetCollector(doc)
user_worksets = collector.OfKind(WorksetKind.UserWorkset)
for i in user_worksets:
result.append(i.Name)
result.append(i.Kind)
OUT = result
I would like to get a list that looks like this: [[name, name, name],[kind, kind, kind]]
thank you,
OUT = [[i.Name for i in user_worksets], [i.Kind for i in user_worksets]]

List of objects with a unique attribute

I have a list of objects that each have a specific attribute. That attribute is not unique, and I would like to end up with a list of the objects that is a subset of the entire list such that all of the specific attributes is a unique set.
For example, if I have four objects:
object1.thing = 1
object2.thing = 2
object3.thing = 3
object4.thing = 2
I would want to end up with either
[object1, object2, object3]
or
[object1, object3, object4]
The exact objects that wind up in the final list are not important, only that a list of their specific attribute is unique.
EDIT: To clarify, essentially what I want is a set that is keyed off of that specific attribute.
You can use a list comprehension and set:
objects = (object1,object2,object3,object4)
seen = set()
unique = [obj for obj in objects if obj.thing not in seen and not seen.add(obj.thing)]
The above code is equivalent to:
seen = set()
unique = []
for obj in objects:
if obj.thing not in seen:
unique.append(obj)
seen.add(obj.thing)
You could create a dict whose key is the object's thing and values are the objects themselves.
d = {}
for obj in object_list:
d[obj.thing] = obj
desired_list = d.values()

Categories

Resources