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).
Related
I have an iterator for creating multiple lists. I need to keep adding the generated list to a dictionary dict1 based on the key value k:
some value here = k
for a in jsoncontent:
list1.append(a["Value"])
dict1.setdefault(k, []).append(list1)
Right now I get:
{k:[[10,11],[12,32,6],[7,4]]}
But I need:
{k:[10,11,12,32,6,7,4]}
How do I merge these lists?
It sounds like you want extend versus append. extend inserts the contents of the list at the end of the list, while append insets its argument, a list in this case. See https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types
I have a dictionary whose values are lists of lists.
mydict = {
"A" : [["gactacgat", "IE"],["gactacgat", "IE"]],
"G" : [["ggctacgat", "EI"],["gactacgat", "IE"]],
"C" : [["gcctacgat", "N"],["gactacgat", "IE"]],
"T" : [["gtctacgat", "IE"],["gactacgat", "IE"]]
}
And I am trying to create a list containing all of the elements in the second column of these 2D lists.
This is what I am doing:
mylist = []
for key in mydict.keys():
for row in mydict[key]:
mylist.append(row[1])
Is there a more efficient way of accessing a specific index from all the lists in these lists of lists than what I have done?
(I apologize if my wording was bad, and any feedback for a better title question is appreciated)
List comprehensions are your friend:
mylist = [row[1] for value in mydict.values() for row in value]
This uses a nested loop, but presumably a bit better optimized. Additionally, using dict.values saves you a key lookup at each iteration of the outer loop, and returns items in the same order as the keys would be.
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.
I've always found Dictionaries to be an odd thing in python. I know it is just me i'm sure but I cant work out how to take two lists and add them to the dict. If both lists were mapable it wouldn't be a problem something like dictionary = dict(zip(list1, list2)) would suffice. However, during each run the list1 will always have one item and the list2 could have multiple items or single item that I'd like as values.
How could I approach adding the key and potentially multiple values to it?
After some deliberation, Kasramvd's second option seems to work well for this scenario:
dictionary.setdefault(list1[0], []).append(list2)
Based on your comment all you need is assigning the second list as a value to only item of first list.
d = {}
d[list1[0]] = list2
And if you want to preserve the values for duplicate keys you can use dict.setdefault() in order to create value of list of list for duplicate keys.
d = {}
d.setdefault(list1[0], []).append(list2)
I'm pretty new to python (couple weeks into it) and I'm having some trouble wrapping my head around data structures. What I've done so far is extract text line-by-line from a .txt file and store them into a dictionary with the key as animal, for example.
database = {
'dog': ['apple', 'dog', '2012-06-12-08-12-59'],
'cat': [
['orange', 'cat', '2012-06-11-18-33-12'],
['blue', 'cat', '2012-06-13-03-23-48']
],
'frog': ['kiwi', 'frog', '2012-06-12-17-12-44'],
'cow': [
['pear', 'ant', '2012-06-12-14-02-30'],
['plum', 'cow', '2012-06-12-23-27-14']
]
}
# year-month-day-hour-min-sec
That way, when I print my dictionary out, it prints out by animal types, and the newest dates first.
Whats the best way to go about sorting this data by time? I'm on python 2.7. What I'm thinking is
for each key:
grab the list (or list of lists) --> get the 3rd entry --> '-'.split it, --> then maybe try the sorted(parameters)
I'm just not really sure how to go about this...
Walk through the elements of your dictionary. For each value, run sorted on your list of lists, and tell the sorting algorithm to use the third field of the list as the "key" element. This key element is what is used to compare values to other elements in the list in order to ascertain sort order. To tell sorted which element of your lists to sort with, use operator.itemgetter to specify the third element.
Since your timestamps are rigidly structured and each character in the timestamp is more temporally significant than the next one, you can sort them naturally, like strings - you don't need to convert them to times.
# Dictionary stored in d
from operator import itemgetter
# Iterate over the elements of the dictionary; below, by
# calling items(), k gets the key value of an entry and
# v gets the value of that entry
for k,v in d.items():
if v and isinstance(v[0], list):
v.sort(key=itemgetter(2)) # Start with 0, so third element is 2
If your dates are all in the format year-month-day-hour-min-sec,2012-06-12-23-27-14,I think your step of split it is not necessary,just compare them as string.
>>> '2012-06-12-23-27-14' > '2012-06-12-14-02-30'
True
Firstly, you'll probably want each key,value item in the dict to be of a similar type. At the moment some of them (eg: database['dog'] ) are a list of strings (a line) and some (eg: database['cat']) are a list of lines. If you get them all into list of lines format (even if there's only one item in the list of lines) it will be much easier.
Then, one (old) way would be to make a comparison function for those lines. This will be easy since your dates are already in a format that's directly (string) comparable. To compare two lines, you want to compare the 3rd (2nd index) item in them:
def compare_line_by_date(x,y):
return cmp(x[2],y[2])
Finally you can get the lines for a particular key sorted by telling the sorted builtin to use your compare_line_by_date function:
sorted(database['cat'],compare_line_by_date)
The above is suitable (but slow, and will disappear in python 3) for arbitrarily complex comparison/sorting functions. There are other ways to do your particular sort, for example by using the key parameter of sorted:
def key_for_line(line):
return line[2]
sorted(database['cat'],key=key_for_line)
Using keys for sorting is much faster than cmp because the key function only needs to be run once per item in the list to be sorted, instead of every time items in the list are compared (which is usually much more often than the number of items in the list). The idea of a key is to basically boil each list item down into something that be compared naturally, like a string or a number. In the example above we boiled the line down into just the date, which is then compared.
Disclaimer: I haven't tested any of the code in this answer... but it should work!