Python : initializing list and dictionary - python

I am new to Python. while initializing a list
mylist = list()
mylist[0]="hello"
gives error .It only works
mylist.append("hello")
but if i do same with dictionary
mydict ={}
mydict["one"]="hello"
it works.
why i dont need to do
mydict['one'].append('hello')
why things are different for different structures.

If you update a dict like this:
d['c'] = 3
... there is no need for d['a'] and d['b'] (or any item at all, for that matter) to be present in that dict. The key of a dictionary item does not imply any specific structural properties of your dict object.
However, if you want to update a list like this:
l[5] = 'a'
... the indexes 0 through 5 absolutely must exist. The index not only serves as a handle for an element in the list, but also has structural properties. If l[5] does exist, you can be absolutely sure that indexes 0 through 4 do as well. And you need that certainty.
Imagine you could do l[5] = 'a' on an empty list. What would len(l) return? 1? 6?
Both cases would cause this to fail:
for i in range(len(l)):
print(l[i])
One can argue that l[<index>] = 'a' could implicitly append that value if index-1 already exists or if the list is empty and the desired index is 0. In order for this to reliably work, you would need to ensure that index-1 exists before adding values like this, while, when using append(), you are guaranteed that your value will be added to the list (except for potential edge cases like memory starvation).

If you add an element to a dictionary you connect to a key.
In your case you connect the element 'hello' to your key 'one'
To add an element to a list you will have to use the function list.append.
You use list[x] to get the element at position x.

Related

Is there a better way to add entries from lists to a dictionary?

As I was studying Python, I came across this task:
Imagine Python did not have built-in support for sets. Show how we
could use dictionaries to represent sets. Write the four set
operations | - ^ & for this new representation of sets.
Below you can see the answer:
First, for the ‘or’ operation, we add entries to the new dictionary
from both input lists:
l1 = [1,2,3,4,5]
l2 = [4,5,6,7,8]
def t_or(l1,l2):
result = {}
for x in l1: result[x] = 0
for x in l2: result[x] = 0
print(result)
So, I'm wondering why have the author used such a strange method to add entries result[x] = 0? Isn't there a better way to do it, maybe using alternatives methods like .add, .insert, etc?
result[key] = value is the way to assign a new pair key:value in a Python dictionary. You don't have to create the entry key first on a Dictionary. If you come from Java, for example, the syntaxis is like:
Map<String, String> result = new HashMap<int, int>();
result.put(1, 0);
As you can see, on Java you are not declaring the key too, the same happens on a lot of languages and that is because of how a dictionary key works.
When you want to retrieve an element from a dictionary, you have to be sure that the key already exists in the dictionary, otherwise it will throw an exception.
The .add or .insert that you have in mind in Python is .append and it is used to add a new element to a list:
my_list = []
my_list.append(0)
So no, there is no a better way or a different way to assign new key:value pairs on a Python dictionary.

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

dictionary update sequence element error

I have several dictionary files, I want this code to open each file and add it to a set, for later comparison and matching. Basically I have a different list of all permutations of all possible characters and I need to know if permutation is in dictionary. But when I try to make a set with all dictionary lines I get this error:
choices = ['s','m','o','k','e','j','a','c','k']
def parsed(choices):
mySet = {}
for item in choices:
filename = self.location + "/dicts/%s.txt" % (item)
mySet.update(open(filename).read().splitlines())
return mySet
I get this error
error: dictionary update sequence element #0 has length 4; 2 is required
Furthermore, I'd like to ask if there's a possible comparison method between two sets of data (9 character permutations, and 9 dictionary files list) that runs in less than 1 minute.
I understand that there are already questions regarding this error, but frankly I'm a beginner and I don't understand how those relate to my code, or how to fix it.
If you write:
mySet = {}
mySet is not a set, but a dictionary (yeah that is confusing). For instance:
>>> type({})
<class 'dict'>
In order to construct an empty set, you should use:
mySet = set()
A set indeed has a function update that takes as input an iterable of elements that are all added to the set. A dictionary on the other hand requires an iterable of tuples (or a dictionary, etc.)

Creating multiple lists within a dictionary using an iteration

I am currently writing a small bit of logic for my HTML page. My aim is to create variables (lists) within an iteration (using the iteration to create the names of said lists as the amount of them will be unknown to the program). I am currently creating the lists like this:
maps={}
currentMap = elements[0].process
counter=0
for i in elements:
if(counter==0):
maps["mapsEle{0}".format(counter)]=[]
counter+=1
if(i.process!=currentMap):
currentMap = i.process
maps["mapEle{0}".format(counter)]=[]
counter+=1
else:
print("No change found, keeping heading the same.")
However as you can probably tell, this does not create a list but a string. I try to print the variables (e.g. mapsEle0) and it returns the variable name (e.g. print(mapsEle0) returns "mapsEle0") this too me is suprising as I would have thought if the dictionary is saving it as a string it would print "[]".
So I am looking for a way to create lists within the dictionary in that iteration I am using there, basically want to just reformat my declaration. Cheers in advance everyone :)
Edit:
As requested here is the code where I attempt to append. Please note I want to append 'i' into the lists and no the dictionary.
for i in maps:
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
#i.append(x)
The syntax of your print statement is wrong, if you want to access the contents of the dictionary, you need to use different notation.
Instead of print('mapsEle0') you need to do print(maps['mapsEle0']).
Update:
Unfortunately your description of what you want and your code are a bit conflicting, so if you can, please try to explain some more what this code is supposed to do.
for i in maps.iterkeys():
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
maps[i].append(x)
This will iterate over all keys of maps ('mapsEle0'...'mapsEleN') and add x to the contained list if the elif condition is fulfilled.
You're printing the string by doing print('mapsEle0').
To print the dict, you must print(maps) - 'll print the whole dictionary, OR, to print a specific key/element print(maps['mapsEle0'])
To elaborate it further here's a interpreter session:
>>> maps = {}
>>> counter = 0
>>> maps["mapsEle{0}".format(counter)]=[]
>>> maps
{'mapsEle0': []}
>>>
>>> print(maps)
{'mapsEle0': []}
>>>
>>> print(maps['mapsEle0'])
[]
>>>
For the append part:
>>> maps['mapsEle1'].append('hello')
>>> print(maps['mapsEle1'])
['hello']
Edit 2: Your statement is still not clear
As requested here is the code where I attempt to append. Please note I
want to append 'i' into the lists and no the dictionary.
I think sobek has got it right - you want to append x to the mapsEle0, mapsEle1 lists, which are keys in maps dictionary.
for i in maps.iterkeys():
for x in elements:
if(x.process!=currentMap):
currentMap=x.process
elif(x.process==currentMap):
maps[i].append(x)

Python: To avoid a TypeError do I need to check if there is a list in a dictionary, then check if that list holds the item?

I have several dictionaries. Sometimes they have with the key thing whose value is a dictionary.
Sometimes that dictionary has the key anotherthing whose value is a string which could be empty. So if I want to check the value of anotherthing to see if A. The key actually exists and B. the value evaluates to something, I need to use three if statements (because any one of the keys could not exist)?
if 'thing' in dictionary_one:
if 'anotherthing' in dictionary_one['thing']:
val = dictionary_one['thing']['anotherthing']
if val:
# Do something with value
In other languages a value will just evaluate to None is there a way around this other than using a Try...Except?
You could chain the lookup with dict.get():
val = dictionary_one.get('thing', {}).get('anotherthing')
if val:

Categories