markdown python_list

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown python_list相关的知识,希望对你有一定的参考价值。

# Dictionary

#### Find value by key
```python
value = d.get(key)
```

##### Check if value exisit
```python
# Nomral dict
if d.get(key):
  d[key] = 0
  
# Nested dict:
if not d[key]:
  d[key] = 0
```

#### Loop each key/value pair
```python
# This work in python3
# For python two just loop through d
for k,v in d.items()
     # do something
```

#### Nested Dictionary (wrapper function)
```python
from collections import defaultdict
nested_dict = lambda: defaultdict(nested_dict)
d = nested_dict()
```

#### Find key by value
- cannot be done directly
- better to check if the value exist first, to prevent keyerror
- value as list -> find the index of the query value -> check the content in the key list
```python
# check if a value exist
value in d.values()
# find key
key = list(d.keys())[list(d.values()).index(value)]
```

#### To dataframe/ Series
```python
# To dataframe, d is the dictionary (python3)
df = pd.DataFrame(list(d.items()),columns=["a","b"])
# In python2 can just give pd.DataFrame a dict items (d.items() return list in python3), but in python3 d.items is a iter item (need to be iterated)
df = pd.DataFrame(d.items(),columns=['a','b'])


# Or to series
s = pd.Series(d)
# series wih it own index
s = pd.Series(d,name="ValueName") 
s.index.name = "KeyName"
s = s.reset_index()  # Free the key out by using new autocrement index
s.to_csv("s.csv")

# This doesn't work becuase DataFrame method accept scalar value only, list/dictionary will not work
pd.DataFrame(d)
```

以上是关于markdown python_list的主要内容,如果未能解决你的问题,请参考以下文章

python PYTHON_LISTS

Python_list

python_list,tuple,dictionary

Python_List,Tuple,Dict,Set

人生苦短_我用Python_list(列表)_002

---python_List---它不是一个简单的数组