Append Values at Dict in Python - python

I have following code and want now to add all items of "Produkt-Name" to a Dictionary
for col_number, element in enumerate(headings):
for row in ws.iter_rows():
if row[col_number].value is None:
continue
else:
if element == "Produkt-Name":
test = {"productname": row[col_number].value}
The Problem is, I only get the last item of it at the dictionary. I also tested the build in update function but got the last index too.

Every time your conditions are met (the two if statements) you create a new dictionary called "test", the proper syntax to add elements to a dict is :
my_dict[new_key] = value
if new_key already exists, then you will overwrite the old value with the new one, without creating a new key/value pair.
Hope this helps.
Also, as others already pointed out, please produce a minimal reproducible example, we at least need the structure of "headings" and what you would expect as an output.

if you want to have all items under the key 'productname' you can use:
test.setdefault("productname", []).append(row[col_number].value)
but if you want to have your values under different keys you need to set different key names.
Edit: for example: test[key1] = value1, test[key2] = value2, ...

Related

Getting keys and values of dictionary if key in list

So I have a dictionary names "ngrams_count". I want to find all keys in this dictionary that are in a list called "words_to_find". I would also like to return the values associated with those keys.
So far, this is what I'm working with
ideasrep = [key for key in words_to_find if key in ngrams_count]
That returns only the keys that are found in the word list.
I'm also looking for a way to return only the key/values pairs for which the value is greater than one. I've tried a similar technique as this:
[(key,values) for key, values in ngrams_count.items() if values > 1]
However, this only seems to work if I stay within the dictionary and I'm running out of ideas... Ideally, I'd like a way to do these two things simultaneously.
Your first version is almost right, you just need to add ngrams_count[key] to the result.
ideasrep = [(key, ngrams_count[key]) for key in words_to_find if key in ngrams_count]
Or you can use the second version, but change the condition to check if the key is in words_to_find.
[(key,values) for key, values in ngrams_count.items() if key in words_to_find]
If words_to_find is big, you should convert it to a set before the list comprehension to make the second version more efficient.

Python: How can I use an enumerate element as a string?

I have a list of dict1.keys() I'm enumerating over and I'd like to use the element as a string.
for i,j in enumerate(dict1.keys()): str(j) = somethingElse
>>> SyntaxError: can't assign to function call
https://dbader.org/blog/python-enumerate describes the enumerate entities as a tuple of: (index, element). The type(j) is <class 'str'>, which I can print, but not use as a variable.
EDIT:
for i,j in enumerate(dict1.keys()): j = somethingElse
EDIT2:
I think the problem may be with pandas. The first line works, not the second.
for i,j in enumerate(dict1.keys()): list1.append(j)
for i,k in enumerate(list1): k = pd.DataFrame(dict1[k]['Values'])
EDIT3:
That second line does work, but only for only ends up with one df, with name 'k' instead of the key. But heres what Im trying to. Each dict converted to a df using its key name:
for i,j in enumerate(dict1.keys()): j = pd.DataFrame(dict1[j]['Values'])
EDIT4:
According to the comments below, I switched to a for loop on the keys (which dont need to be explicitly called), but it still won't use the element 'i' as a variable. However, from the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:
dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])
..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.
use elements in a list for dataframe names
Because you are generating your pandas dataframe dynamically inside a for loop so at the end when you print j it will show you the last generated dataframe. You should store your dataframe in list Try using this:
listOfFrame = []
for j in dict.keys():
j = pd.DataFrame(dict[j]['Values'])
listOfFrame.append(j)
Indeed j will be a str (or whatever else type of key you are using in dict).
The actual problem is with the loop body, as the error message states:
str(j) = somethingElse
is not valid Python. The left hand side is a call to the str function, so you cannot assign a value to it.
Based on the comments you want neither enumerate nor to iterate over the dict keys. Instead, you want to iterate over its values:
dfs = []
for val in dict1.values():
dfs.append(pd.DataFrame(val['Values']))
However, this would normally written without an explicit loop in Python, for instance by using list comprehension:
dfs = [pd.DataFrame(val['Values']) for val in dict1.values()]
From the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:
dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])
..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.
use elements in a list for dataframe names

Using a for loop to print keys and/or values in a dictionary for python. Looking for logical thinking explanation thanks :D

My problem is understanding why these certain lines of code do what they do. Basically why it works logically. I am using PyCharm python 3 I think.
house_Number = {
"Luca": 1, "David": 2, "Alex": 3, "Kaden": 4, "Kian": 5
}
for item in house_Number:
print(house_Number[item]) # Why does this print the values tied with the key?
print(item) # Why does this print the key?
This is my first question so sorry I don't know how to format the code to make it look nice. My question is why when you use the for loop to print the dictionary key or value the syntax to print the key is to print every item? And what does it even mean to print(house_Number[item]).
They both work to print key or value but I really want to know a logical answer as to why it works this way. Thanks :D
I'm not working on any projects just starting to learn off of codeacademey.
In Python, iteration over a dictionary (for item in dict) is defined as iteration over that dictionary's keys. This is simply how the language was designed -- other languages and collection classes do it differently, iterating, for example, over key-value tuples, templated Pair<X,Y> objects, or what have you.
house_Number[item] accesses the value in house_Number referenced by the key item. [...] is the syntax for indexing in Python (and most other languages); an_array[2] gives the third element of an_array and house_Number[item] gives the value corresponding to the key item in the dictionary house_Number.
Just a side note: Python naming conventions would dictate house_number, not house_Number. Capital letters are generally only used in CamelCasedClassNames and CONSTANTS.
In python values inside a dictionary object are accessed using dictionay_name['KEY']
In your case you are iterating over the keys of dictionary
Hope this helps
for item in dic:
print(item) # key
print(dic[item]) # value
Dictionaries are basically containers containing some items (keys) which are stored by hashing method. These keys just map to the values (dic[key]).
Like in set, if you traverse using for loop, you get the keys from it (in random order since they are hashed). Similarly, dictionaries are just sets with a value associated with it. it makes more sense to iterate the keys as in sets (too in random order).
Read more about dicionaries here https://docs.python.org/3/tutorial/datastructures.html#dictionaries and hopefully that will answer your question. Specifically, look at the .items() method of the dictionary object.
When you type for item in house_Number, you don’t specify whether item is the key or value of house_Number. Then python just thinks that you meant the key of house_Number.
So when you do the function print(house_Number[item]), you’re printing the value because your taking the key and finding the value. In other words, you taking each key once, and finding their values, which are 1, 2, 3, 4, 5, 6
The print(item) is just to print the item, which are the keys, "Luca", "David", "Alex", "Kaden", "Kian"
Because the print(house_Number[item]) and print(item) alternating, you get the keys and values alternating, each on a new line.

Eliminating repetition among the dictionary in python [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am working on creating a dictionary in python but the thin line between list and python is confusing me alot. What i have is
values = []
where in i'll store the values as
values.append({newvalue : oldvalue})
the list or dictionary whatever it is, it's working but is not checking for repetition among itself. so what i did is
for i in range(len(values)):
if ((newvalue not in values[i])):
values.append({newvalue: oldvalue})
but this is not working. why? and how can i resolve this? and if you have time please explain how different is list with dictionary and what do i have in my code. a list or a dictionary?
Thanks
first of all, if you want an empty dictionary, dont do values = [] that will make a list, instead do
values = {}
when adding to a dictionary, do this
mydict[mykey] = myvalue
when checking to see if something is already in the keys do this
if newkey not in mydict:
print('this will not overwrite anything')
I think you are misunderstanding the concept of a dictionary
When you do this key will be your dictionary key, and val will be your dictionary value. A dictionary is a combination of pairs of terms in the order {key: value} so if you do myDict[key] you will get value
If you want to add to a dictionary while making sure that you aren't overwriting anything, this simple example will do that for you.
if newkey not in mydict:
mydict[newkey] = newvalue
A list is a sequence of elements. Elements are numbered (and ordered) by an implicit index. It is this index what you mainly use to identify the elements within the list. Elements can be repeated. Indexes are not. If you assign a new value to any element (identified by its index), the new value will replace the old one.
Example: In ["day", "midnight", "night", "noon", "day", "night"], (implicit) indexes are 0, 1, 2, 3, 4, and 5. list[0] is "day", list[1] is "midnight", list[4] is also "day", and so on. list[3]= "midday" changes the value of element 3 from "noon" to "midday". list.append("afternoon") adds an element at the end of the list, which becomes list[6].
Lists are useful to represent:
Collections of (possibly repeated) elements.
Collections of elements when their order (position in the list) is
important.
A dictionary is a collection of elements with no intrinsic order. Elements within the dictionary are identified by explicit keys. As with lists, elements can be repeated, but keys can not, and if you assign a new value to any element (identified by its key), the new value will replace the old one.
Example: In {"dia": "day", "medianoche": "midnight", "noche": "night", "mediodia": "noon", "tag": "day", "nacht": "night"} keys are "dia", "medianoche", "noche", "mediodia", "tag", and "nacht". dict["dia"] is "day", dict["medianoche"] is "midnight", dict["tag"] is also "day", and so on. dict["mediodia"]= "midday" would replace the value of the element identified by "mediodia" from "noon" to "midday", and dict["tardes"]= "afternoon" would add an element for key "tardes" with value "afternoon", as there was no previous element identified by "tardes". This is different to lists, which require append to add elements.
Dictionaries are useful to represent:
Associations ("translations", "equivalencies") of data (i.e. of keys
into elements, but not the other way round because elements can be duplicate).
"Lists" with "indexes" that are not integer values (but strings, floating point values, etc)
"Sparse lists", where keys are integers, but the vast mayority of
elements is None. This is usually done to save memory.
In your code, you are creating an empty list
values = []
Then, you create a dictionary {newvalue : oldvalue} with only one element oldvalue whose key is newvalue. And finally, you add this dictionary to the list through method append. Yes, in Python it's absolutely valid to have dictionaries as elements of lists and lists as elements of dictionaries (or even their keys). However, this is most probably not what you intended to achieve.
If what you want is a list with elements newvalue and oldvalue, you should have written:
values= []
values.append(newvalue)
values.append(oldvalue)
or simply
values= [newvalue, oldvalue]
If what you want is a dictionary with a single element oldvalue identified by key newvalue, you should have written:
values= {}
values[newvalue]= oldvalue
or simply
values= {newvalue: oldvalue}
Your code is not working because values is initially empty, so the for loop will not iterate at all. What you probably intended is:
values= {}
if newvalue not in values.keys(): # "newvalue not in values" is shorter but can be misleading
values[newvalue]= oldvalue
or
values= {}
if values[newvalue] is None:
values[newvalue]= oldvalue
Additionally, values.update({newvalue: oldvalue}) is a synonym to values[newvalue]= oldvalue, but you seem to be trying to use a mix of this form and lists by doing values.append({newvalue: oldvalue}). Again, a dictionary is not a list of single-element dictionaries (which is what you were building and trying to manipulate).

How to work around needing to update a dictionary

I need to delete a k/v pair from a dictionary in a loop. After getting RuntimeError: dictionary changed size during iteration I pickled the dictionary after deleting the k/v and in one of the outer loops I try to reopen the newly pickled/updated dictionary. However, as many of you will probably know-I get the same error-I think when it reaches the top of the loop. I do not use my dictionary in the outermost loop.
So my question is-does anyone know how to get around this problem? I want to delete a k/V pair from a dictionary and use that resized dictionary on the next iteration of the loop.
to focus the problem and use the solution from Cygil
list=[27,29,23,30,3,5,40]
testDict={}
for x in range(25):
tempDict={}
tempDict['xsquared']=x*x
tempDict['xinverse']=1.0/(x+1.0)
testDict[(x,x+1)]=tempDict
for item in list:
print 'the Dictionary now has',len(testDict.keys()), ' keys'
for key in testDict.keys():
if key[0]==item:
del testDict[key]
I am doing this because I have to have some research assistants compare some observations from two data sets that could not be matched because of name variants. The idea is to throw up a name from one data set (say set A) and then based on a key match find all the names attached to that key in the other dataset (set B). One a match has been identified I don't want to show the value from B again to speed things up for them. Because there are 6,000 observations I also don't want them to have to start at the beginning of A each time they get back to work. However, I can fix that by letting them chose to enter the last key from A they worked with. But I really need to reduce B once the match has been identified
Without code, I'm assuming you're writing something like:
for key in dict:
if check_condition(dict[key]):
del dict[key]
If so, you can write
for key in list(dict.keys()):
if key in dict and check_condition(dict[key]):
del dict[key]
list(dict.keys()) returns a copy of the keys, not a view, which makes it possible to delete from the dictionary (you are iterating through a copy of the keys, not the keys in the dictionary itself, in this case.)
Delete all keys whose value is > 15:
for k in mydict.keys(): # makes a list of the keys and iterate
# over the list, not over the dict.
if mydict[k] > 15:
del mydict[k]
Change:
for ansSeries in notmatched:
To:
for ansSeries in notmatched.copy():

Categories